PHPHtmlParser - $dom->find() only returning first result

2.3k Views Asked by At

I am using the php-html-parser package (based simplehtmldom) loaded in via Composer and parsing an HTML string, however when using the $dom->find() to loop through all of the elements I am searching for, it is only detecting the first element (out of 29).

require __DIR__ . "/vendor/autoload.php";
$dom = new PHPHtmlParser\Dom;
$dom->load($result); // $result is the output of a cURL request
$classes = $dom->find('li[class=SPECIALCLASS]');
echo count($classes);
foreach($classes as $class){
   echo $class->text;
}

Output: 1

Sample HTML:

<li class="SPECIALCLASS "></li>
<li class="SPECIALCLASS SOMEOTHERCLASS "></li>

EDIT: Dropping the class selector completely results in 5/29 li tags being returned, so I have a feeling there is something bigger at play here.

2

There are 2 best solutions below

2
Mehdi Rahimi On

Try something like this:

$dom->find('li[contains(@class, "SPECIALCLASS")]');

instead of:

$dom->find('li[class=SPECIALCLASS]');
0
Raj Omer Mustafa On

none of above solution works for me. I just do a hack

while($dom->find("li.SPECIALCLASS", 0)) {
    $class = $dom->find("li.SPECIALCLASS", 0);
    echo $class->text;
    $class->delete();
    unset($class);
}

as PHPHtmlParser\Dom read only single line in both cases find("li.class") and find("li.class", 0).
so I read first element get data and delete it. in next iteration I will get next class using this logic I loop through all classes