PHP handle errors

后端 未结 2 1666
迷失自我
迷失自我 2021-01-14 04:56

Using this code with simplehtmldom script (http://simplehtmldom.sourceforge.net/manual.htm):

function file_get_html() {
    $dom = new simple_html_dom;
    $         


        
相关标签:
2条回答
  • 2021-01-14 04:58

    Hi You need to check for the 404 Not Found message as there is returned an array in any case.

    function url_exists($url){
    if ((strpos($url, "http")) === false) $url = "http://" . $url;
    $headers = @get_headers($url);
    //print_r($headers);
    if (is_array($headers)){
        //Check for http error here....should add checks for other errors too...
        if(strpos($headers[0], '404 Not Found'))
            return false;
        else
            return true;    
    }         
    else
        return false;
    }
    
    0 讨论(0)
  • 2021-01-14 05:03

    Try putting try-catch like this in your function:

    try{
        $dom->load(call_user_func_array('file_get_contents', $args), true);
        return $dom;
    }
    catch(Exception $e){
      //echo $e->getMessage();
      throw new Exception('could not load the url');
    }
    

    Update:

    Or you can use this function to see if the remote link really exists:

    function url_exists($url){
        if ((strpos($url, "http")) === false) $url = "http://" . $url;
        if (is_array(@get_headers($url)))
             return true;
        else
             return false;
    }
    

    Here is how you can use above function:

    function file_get_html() {
        $args = func_get_args();
    
        if (url_exists($args)) {
          $dom = new simple_html_dom;
          $dom->load(call_user_func_array('file_get_contents', $args), true);
          return $dom;
        }
        else {
          echo "The url isn't valid";
          return false;
        }
    }
    
    0 讨论(0)
提交回复
热议问题