'get elements by name from a DOMNodeList
In the following code, I retrieve with DOM a list of nodes from an xml document. Then I would like to select, by their tag name, some of these nodes.
$index = new DOMDocument();
$index->load('index.xml');
$xpath = new DOMXpath($index);
$related_notions = $xpath->query("/index/notion[name='" . $name . "']/relations/*"); // the variable $name is dynamically defined previously in the script
foreach ($related_notions->getElementsByTagName("superordinate") as $item) {
// do something
}
I get the following error: Uncaught Error: Call to undefined method DOMNodeList::getElementsByTagName()
I don't understand why the method getElementsByTagName() is not defined for DOMNodeList. After all, getting elements by their name seems to me something obvious that one might want to do with a node list. At any rate, my actual question is: How can I do what I want to do? That is, in the absence of the method getElementsByTagName(), how do I get elements by tag name from a node list?
Thanks in advance for your help!
Solution 1:[1]
I found a solution to my problem, namely to test for the nodeName with an if statement inside the foreach:
$index = new DOMDocument();
$index->load('index.xml');
$xpath = new DOMXpath($index);
$related_notions = $xpath->query("/index/notion[name='" . $name . "']/relations/*");
foreach ($related_notions as $item) {
if ($item->nodeName == "superordinate") {
// do something
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wolfhart |
