Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use XPath to check if <Success /> node exists

Tags:

php

xml

xpath

I am working with PHP and XPath connecting to a remote XML based API. A sample response from the server is as this one below.

    <OTA_PingRS>
        <Success />
        <EchoData>This is some test data</EchoData>
    </OTA_PingRS>

You can see there is no starting tag <Success> so how do I search for the existance of <Success /> using Xpath?

Thanks Simon

like image 677
PrestonDocks Avatar asked Sep 05 '12 20:09

PrestonDocks


1 Answers

The <Success /> element is an empty element, meaning it has no value. It is both, Start and End Tag.

You can test for existence of nodes with the XPath function boolean()

The boolean function converts its argument to a boolean as follows:

  • a number is true if and only if it is neither positive or negative zero nor NaN
  • a node-set is true if and only if it is non-empty
  • a string is true if and only if its length is non-zero
  • an object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type

To do that with DOMXPath you need to use the DOMXPath::evaluate() method because it will return a typed result, in this case a boolean:

$xml = <<< XML
<OTA_PingRS>
    <Success />
    <EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;

$dom = new DOMDocument;
$dom->loadXml($xml);

$xpath = new DOMXPath($dom);
$successNodeExists = $xpath->evaluate('boolean(/OTA_PingRS/Success)');

var_dump($successNodeExists); // true

demo


Of course, you can also just query for /OTA_PingRS/Success and see whether there are results in the returned DOMNodeList:

$xml = <<< XML
<OTA_PingRS>
    <Success />
    <EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;

$dom = new DOMDocument;
$dom->loadXml($xml);

$xpath = new DOMXPath($dom);
$successNodeList = $xpath->evaluate('/OTA_PingRS/Success');

var_dump($successNodeList->length);

demo


You can also use SimpleXML:

$xml = <<< XML
<OTA_PingRS>
    <Success />
    <EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;

$nodeCount = count(simplexml_load_string($xml)->xpath('/OTA_PingRS/Success'));

var_dump($nodeCount); // 1
like image 106
Gordon Avatar answered Nov 15 '22 17:11

Gordon