在简单的HTML DOM中处理错误的另一种方法


other method of handle errors in simple html dom

这是一个简单的代码:(简单的html dom(

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

如果div.newsBody 剂量在谷歌页面中不存在,我们会收到此错误:

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

现在我想处理此错误:

 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!";

这是真的吗?或者有更好的解决方案吗?

就是

这样完成的,但不要重复自己:

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