How to check if a SimpleHTMLDom element does not exist

懵懂的女人 提交于 2019-12-31 00:29:09

问题


SimpleHtmldom can be used to extract the contents of the first element with class description.

$html = str_get_html($html);
$html->find('.description', 0)

However if this class does not exist, PHP will throw an error

Trying to get property of non-object

I tried

if(!isset($html->find('.description', 0))) {
    echo 'not set';
}

and

if(!empty($html->find('.description', 0))) {
    echo 'not set';
}

but both gives the error

Can't use method return value in write context

What is the proper way to check if the element exist?


回答1:


if(($html->find('.description', 0))) {
    echo 'set';
}else{
    echo 'not set';
}

http://www.php.net/manual/en/control-structures.if.php




回答2:


According to the SimpleHtmlDOM Api str_get_html($html) expects a string as input. First check with a html validator if your code is well formatted.

$htmlObj = str_get_html($html);
if (!is_object($htmlObj)) return; // catch errors 

// or wrap further code in 
if (is_object($htmlObj)) { /* doWork */ }



回答3:


$avalable = ($element->find('span.sold-out-text', 0)) ? 1 : 0;

It works for me.




回答4:


for me none of above solution worked and finally i checked like this

$html = str_get_html($html);

if($html){
    //html found
}else{
    //html not found
}


来源:https://stackoverflow.com/questions/12071213/how-to-check-if-a-simplehtmldom-element-does-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!