Marcello Impastato Marcello Impastato - 29 days ago 10
PHP Question

How i can get content inside two tag in a xml file?

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

<book id="1">
<title>...</title>
<author>...</author>
</book>
<book id="2">
<title>...</title>
<author>...</author>
</book>
<book id="3">
<title>...</title>
<author>...</author>
</book>


Giving to input tagname as "book" and id as 2, it should return all which inside it, in this case:

<title>...</title>
<author>...</author>


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

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;
$dom->loadXML($str);

$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 final part of code loop throught child of selected element to get html of them.

Check result in demo

Comments