How to check if a SimpleHTMLDom element does not e

2019-02-23 13:20发布

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?

4条回答
在下西门庆
2楼-- · 2019-02-23 13:37
if(($html->find('.description', 0))) {
    echo 'set';
}else{
    echo 'not set';
}

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

查看更多
唯我独甜
3楼-- · 2019-02-23 13:40

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 */ }
查看更多
贼婆χ
4楼-- · 2019-02-23 13:44
$avalable = ($element->find('span.sold-out-text', 0)) ? 1 : 0;

It works for me.

查看更多
霸刀☆藐视天下
5楼-- · 2019-02-23 13:49

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
}
查看更多
登录 后发表回答