How to get a specific tag in a DOMDocument in PHP?
domdocument, php, xml
Solution
This is the kind of problem that PHP's `DOMDocument` class excels at. First load the XML string using `loadHTML()` method, and then use an XPath expression to traverse the DOM tree:
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$item_tags = $xpath->query('//tag2/item');
foreach ($item_tags as $tag) {
echo $tag->tagName, PHP_EOL; // example
}
Online demo
Problem
I have variable documents that I need to modify on the fly. For example, I could have a document as follows: ``` <!--?xml version="1.0"?--> <item> <tag1></tag1> </item> <tag2> <item></item> <item></item> </tag2> ``` This is very simplified, but I have tags with the same name at different levels. I want to get the item tags within 'tag2'. The actual tags in the files I am given have unique IDs to differentiate them as well as some other attributes. I need to find the tag, comment it out, and save the xml. I was able to get DOMDocument to return the 'tag2' node, but I'm not sure how to access the item tags within that structure.