Reputation: 567
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
Reputation: 97682
Passing a DomNode to foreach will not allow you to iterate through its childen, you can easily get the list of li
s 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 />';
}
?>
Upvotes: 8