How to get a specific tag in a DOMDocument in PHP?

I have variable documents that I need to change 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 element tags in tag2. The actual tags in the files that I give have unique identifiers to distinguish 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 a DOMDocument to return a "tag2" node, but I'm not sure how to access the element tags inside this structure.

+6
source share
3 answers

This is the problem faced by the PHP DOMDocument class. First load the XML string using the loadHTML() method, and then use the XPath expression to move 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 } 

Demo version

+4
source
 <?php $tag= new DOMDocument(); $tag->loadHTML($string); foreach ($tag->getElementsByTagName("tag") as $element) { echo $tag->saveXML($element); } ?> 

can help you .try it

+1
source
 $DOMNode -> attributes -> getNamedItem( 'yourAttribute' ) -> value; 
0
source

All Articles