PHP processing errors

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

function file_get_html() {
    $dom = new simple_html_dom;
    $args = func_get_args();
    $dom->load(call_user_func_array('file_get_contents', $args), true);
    return $dom;
}

$url = 'http://site.com/';
$html = file_get_html($url);

How to handle erros in parts file_get_html($url)? Now, if the page does not exist, it shows errors in the browser window. I prefer to catch them and show my text, for example:

if(some error happened on file_get_html($url)) {
   $errors = true;
} else {
   html = file_get_html($url);
}

Thank.

+3
source share
2 answers

Try adding try-catchto this 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');
}

Strike>

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 the 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;
    }
}
+4
source

Hi. You need to check the 404 Not Found message, as the array is returned anyway.

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;
}
+6
source

Source: https://habr.com/ru/post/1759127/


All Articles