Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 280
Trim Avatar asked Feb 18 '14 14:02

Trim


2 Answers

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

like image 136
Amal Murali Avatar answered Nov 03 '22 02:11

Amal Murali


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

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

may be helps you .try it

like image 21
Ferrakkem Bhuiyan Avatar answered Nov 03 '22 04:11

Ferrakkem Bhuiyan