简体   繁体   中英

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

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.

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

<?php
$tag= new DOMDocument();
$tag->loadHTML($string);

foreach ($tag->getElementsByTagName("tag") as $element) 
{
    echo $tag->saveXML($element);
}
?>

may be helps you .try it

$DOMNode -> attributes -> getNamedItem( 'yourAttribute' ) -> value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM