Marcello Impastato Marcello Impastato - 1 year ago 73
PHP Question

How to get innerHTML of XML tag has specific id attribute using php?

Having a xml file, how i can get content with/without attribute? For example having something as:

<book id="1">
<book id="2">
<book id="3">

Giving to input tagname as
, it should return all which inside it, in this case:


I have solved problem looking xml file as a string and working with the string but i want ask is possible to do some using a xml-file without scroll directly all content.
In real i have big xml file (something as 30-40 MB) and simply want search a content in it giving as coordinates tag-name and (if present) the attribute/s.
The structure of file not is a "constant".

Answer Source

DOMXPath::query is a good method to filter selected elements by XPath. You can select elements has specific attribute. The code find book tag that value of id attribute of it is 2.

$dom = new DOMDocument;

$xpath = new DOMXPath($dom);
$book = $xpath->query("//book[@id='2']")->item(0);

foreach($book->childNodes as $node) {
   @$html .= $dom->saveHTML($node);
echo $html;

Note that the final part of code loop through childs of selected element to get html of them.

Check result in demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download