I'm trying to parse a xml file with information about some users. Something like this
users.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user>
<name>Alexander</name>
<email>[email protected]</email>
</user>
<user>
<name>Tyler</name>
<email>[email protected]</email>
</user>
</users>
I'm using DOMXpath
to extract all users inside this xml, and all of this fields.
In xml file, I have 15 users and when I search all fields about one user in this code
$username = $xpath->query ( '//email', $users->item(0) );
I got 15 length, instead of 1. I mean query
is searching in all xml instead of looking for the actual user.
What I'm doing wrong?
xml_query.php
$xml = new DOMDocument();
$xml->loadXML( $xml_content );
$xpath = new DOMXPath($xml);
$users = $xpath->query( '//user' );
var_dump( $users->item(0) );
$username = $xpath->query ( '//email', $users->item(0) );
var_dump( $username );
Because
//email
select all elements in the document but you need to select elements within the current context. Remove//
from query expression.See result in demo