I would like to get parent data when my child value matches with "id22"
<servers>
<someservers>
<owner>id0</owner>
<serverCode>fefwewf</serverCode>
<address>345345</address>
<authCertHash>efref</authCertHash>
<authCertHash>erferf=</authCertHash>
<client>id1</client>
<client>id22</client>
</someservers>
<someservers>
<owner>id33</owner>
<serverCode>f</sewewefrverCode>
<address>234234234</address>
<authCertHash>sdfs</authCertHash>
<client>id27</client>
</someservers>
</server>
Currently im trying as following:
$server = $xml -> xpath('//someservers//client='id22');
echo $server->address;
But it's not working, I get error:
Trying to get property of non-object in...
I hope to get output:
345345
SimpleXMLElement::xpath()
only supports Xpath expressions that return an node list, so it can convert them into an array of SimpleXMLElement
instances.
@andersson already explained that you expression only returns the existence of the specified client element. You need to use a condition. This will return an array with matching SimpleXMLElement
objects as the elements.
$servers = new SimpleXMLElement($xml);
$server = $servers->xpath('//someservers[client="id22"]')[0];
echo $server->address;
Output:
345345
DOMXpath::evaluate()
is able to return the scalar value directly:
$document = new DOMDocument();
$document->loadXml($xml);
$xpath= new DOMXpath($document);
echo $xpath->evaluate('string(//someservers[client="id22"]/address)');
Your XPath
//someservers//client='id22
intend to return boolean true
/false
value, but not element or its text content
Try to use below XPath
expression
//someservers[client='id22']/address/text()
that should return required "345345"