How to check if a SimpleHTMLDom element does not exist
Asked Answered
O

3

6

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?

Opaline answered 22/8, 2012 at 10:32 Comment(2)
empty cannot operat directly on the value. $html->find() returns an empty array if element was not found. So the solution offered by Death should be valid.Romanfleuve
FYI: blog.futtta.be/2012/05/31/…Deedradeeds
E
12
if(($html->find('.description', 0))) {
    echo 'set';
}else{
    echo 'not set';
}

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

Excoriation answered 22/8, 2012 at 10:36 Comment(2)
not work Fatal error: Call to a member function find() on a non-objectQuinton
@AnassElFakir *_get_html functions may return false :)Excoriation
Z
1

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 */ }
Zoology answered 22/8, 2012 at 10:43 Comment(0)
P
0
$avalable = ($element->find('span.sold-out-text', 0)) ? 1 : 0;

It works for me.

Pronouncement answered 9/8, 2015 at 16:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.