Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a SimpleHTMLDom element does not exist

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?

like image 989
Nyxynyx Avatar asked Aug 22 '12 10:08

Nyxynyx


2 Answers

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

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

like image 176
undone Avatar answered Nov 20 '22 01:11

undone


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 */ }
like image 41
Chapter2 Avatar answered Nov 20 '22 01:11

Chapter2