Php DOM getAttribute

Okay, so I have a strange case that I just can't understand.

I want to analyze a list on a website. HTML looks something like this:

<!-- ... -->
<ul id="foo">
    <li data-text="item 1">Blabla</li>
    <li data-text="item 2">Blabla</li>
    <li data-text="item 3">Blabla</li>
    <li data-text="item 4">Blabla</li>
</ul>
<!-- ... -->

Now I want to capture all the items in the list. For this, I use the DOMDocument class. So far this has worked well:

$dom = new DOMDocument();

if (!$dom->loadHTML($html)) {
    die ('Could not parse...');
}

$list = $dom->getElementById('foo');
$items = $list->childNodes;
foreach ($items as $item) {
     print_r($item);
}

But now I'm looking for a simple method to read an attribute data-text. I have done this:

foreach ($items as $item) {
     echo $item->getAttribute('data-text');
}

This works fine for the very first element, but then it issues a foreach loop. Output:

item 1
Fatal error: call to undefined method DOMText :: getAttribute () in example.php on line 44

I do not understand how a method call getAttributechanges the context of a foreach loop. So here are two questions:

  • How to call a method that scooped up my foreach loop? Secondly, what is the most elegant workaround?
  • , $item->attributes with foreach, data-text , ?!
+5
1

, ul , li , . , node,

foreach ($items as $item) {
         if ($item->nodeType == XML_ELEMENT_NODE)
         echo $item->getAttribute('data-text');
}

getElementsByTagName(), , , li.

$items = $list->getElementsByTagName('li');
foreach ($items as $item) {
    echo $item->getAttribute('data-text');
}
+8

All Articles