Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP爬虫:检查对象是否存在_Php_Dom_Web Crawler - Fatal编程技术网

PHP爬虫:检查对象是否存在

PHP爬虫:检查对象是否存在,php,dom,web-crawler,Php,Dom,Web Crawler,我在查找某些类/元素的页面上运行php脚本,如果类/元素不存在,有时可能会出现“试图获取非对象的属性”错误 我想知道如何处理此错误,以便在语句或为空时,使用将自己的空值分配给变量 查看下面我的代码,以便更好地理解我的意思 在if($size=$elem->find('.size',0)->明文)行上,由于类大小不存在,“history”元素将抛出错误 功能:获取信息 function getInfo($link){ $page = file_get_html($link);

我在查找某些类/元素的页面上运行php脚本,如果类/元素不存在,有时可能会出现“试图获取非对象的属性”错误

我想知道如何处理此错误,以便在
语句或
为空时,使用
将自己的空值分配给变量

查看下面我的代码,以便更好地理解我的意思

if($size=$elem->find('.size',0)->明文)
行上,由于类大小不存在,“history”元素将抛出错误

功能:获取信息

function getInfo($link){
   $page = file_get_html($link);        

   if($page){       
      $categoryLink = array();
      $categoryName = array();
      $categorySize = array();

      if($container = $page->find('.infoContainer',1)){

         foreach($container->find('.element') as $elem){

            if($link = $elem->find('a',0)->href){   
               $categoryLink[] = $link;
            }else{
               $categoryLink[] = "";
            }

            if($name = $elem->find('.name',0)->plaintext){
               $categoryName[] = $name;
            }else{
               $categoryName[] = "";
            }

            if($size = $elem->find('.size',0)->plaintext){
               $categorySize[] = $size;
            }else{
               $categorySize[] = 0;
            }
         }
      }
   }
}
www.example.com

<div class='infoContainer'>
   <div class='element'>
      <a href='www.example.com/physics'>
      <div class='name'>physics</div>
      <div class='size'>1000</div>
   </div>
   <div class='element'>
      <a href='www.example.com/math'>
      <div class='name'>math</div>
      <div class='size'>800</div>
   </div>
   <div class='element'>
      <a href='www.example.com/history'>
      <div class='name'>history</div>
   </div>

</div>

在尝试访问其属性之前,应首先检查
find
的结果:

$result = $elem->find('foo', 0);
if ($result) {
    $something = $result->property;
}

这适用于
foreach
中的所有3个检查,仅具有不同的参数名称等。

@mk_89:不,这肯定不是您正在做的。您正在对
$result->property
进行检查,而不是对
$result
本身进行检查。啊,我发现了问题,我不应该将其转换为if语句的纯文本。
$result = $elem->find('foo', 0);
if ($result) {
    $something = $result->property;
}