symfonydevpl
symfonydevpl

Reputation: 567

PHP DOM get items from first ul element

I have html file which looks like this:

<ul>
 <li>item 1</li>
 <li>item 2</li>
 <li>item 3</li>
</ul>
<ul>
 <li>smth 1 2 3..</li>
 <li>another</li>
<ul>
<ul>
 <li>smth 1 2 3..</li>
 <li>another</li>
<ul>

I am trying to get elements only from first ul list. I am using this code, but it returns errors:

<?php
    $dom = new DOMDocument();
            $dom->loadHTML($data);
            $postalCodesList = $dom->getElementsByTagName('ul');
            foreach ($postalCodesList->item(0) as $postalCodesList) {
                 echo $postalCodesList->nodeValue.'<br />';

            }
?>

Upvotes: 3

Views: 6037

Answers (1)

Musa
Musa

Reputation: 97682

Passing a DomNode to foreach will not allow you to iterate through its childen, you can easily get the list of lis and iterate through them.

<?php
    $dom = new DOMDocument();
    $dom->loadHTML($data);
    $postalCodesList = $dom->getElementsByTagName('ul');
    foreach ($postalCodesList->item(0)->getElementsByTagName('li') as $postalCodesList) {
        echo $postalCodesList->nodeValue.'<br />';                    
    }
?>

DEMO

Upvotes: 8

Related Questions