Trim
Trim

Reputation: 373

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.

Upvotes: 6

Views: 2360

Answers (3)

Amal Murali
Amal Murali

Reputation: 76666

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

Upvotes: 5

Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

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

Upvotes: 0

Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

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

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

may be helps you .try it

Upvotes: 1

Related Questions