Search code examples
phpsimple-html-dom

other method of handle errors in simple html dom


This is a simple code: (simple html dom)

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

$title = $html->find('div.newsBody h1', 0)->plaintext;
echo "Title:". $title;

If div.newsBody dosen't exist in google page we get this error:

Notice: Trying to get property of non-object in...

Now I want to handle this error:

 if(file_get_html('http://google.com'))
 { 
     $html = file_get_html('http://google.com');
     if($html->find('div.newsBody h1', 0))
         echo $html->find('div.newsBody h1', 0)->plaintext;
     else
         echo "No div found!";
 }
 else
     echo "No webpage Access!";

Is it true? or IS there a better solution?


Solution

  • That's how it's done, but don't repeat yourself:

    if($div = $html->find('div.newsBody h1', 0))
      echo $div->plaintext;