1

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.

Lorenzo Aiello
  • 497
  • 1
  • 7
  • 18
  • What will happen if you try: foreach($dom->find('li[class=SPECIALCLASS]') as $element) { } – HZS Oct 04 '16 at 16:26
  • I just installed php-html-parser and tested your script with the sample input and it returns 2 as expected. So maybe the problem is with the sample HTML. – Olaf Dietsche Oct 04 '16 at 17:12

2 Answers2

1

Try something like this:

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

instead of:

$dom->find('li[class=SPECIALCLASS]');
Mehdi Rahimi
  • 1,453
  • 5
  • 20
  • 31
  • This appears to have significantly helped, but I'm now getting 7 results (out of 29) and when I try to loop through them to see what the results are, my find()->text or find()->innerHTML isn't working all of a sudden – Lorenzo Aiello Oct 04 '16 at 16:36
  • Post the code so we can see what can be the issue. @laiello – Mehdi Rahimi Oct 04 '16 at 17:13
0

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

Raj Omer Mustafa
  • 81
  • 1
  • 1
  • 5