简体   繁体   中英

Extract Data from XML with namespace

I tried below code to extract data from below XML but got an empty string.

XML

 <s:envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
      <s:body>
           <ns2:checkbalanceresponse xmlns:ns2="http://booking.us.org/">
                <return>
                     "<Balance><Airline><AirlineName>BUDDHA AIR</AirlineName><AgencyName>GANDAKI INTERNATIONAL TRAVELS KTM(STO)</AgencyName><BalanceAmount>5555</BalanceAmount></Airline></Balance>"
                 </return>
            </ns2:checkbalanceresponse>
       </s:body>
 </s:envelope>

Code

 $doc = simplexml_load_string($response);
 $doc->registerXPathNamespace('ns2', 'http://booking.us.org/');
 $nodes = $doc->xpath('//ns2:checkbalanceresponse');
 $nodes = $nodes[0]->return;
 $obj = simplexml_load_string($nodes); 
 var_dump($obj->Balance->Airline->AirlineName);     //null 

You can do it like this.

Problem: $nodes[0]->return; This statement will return an object instead of string.

Try this code snippet here

$doc = simplexml_load_string($string);
$doc->registerXPathNamespace('ns2', 'http://booking.us.org/');
$nodes = $doc->xpath('//ns2:checkbalanceresponse');
$nodes=$nodes[0]->return; //here $nodes gives you an object instead of html

echo $nodes->Balance->Airline->AirlineName;

As your content of <return> is already XML, instead of having to read it as a string and then convert it, your first simplexml_load_string has already done all of the work. You can access the value straight from your XPath...

$doc = simplexml_load_string($response);
$doc->registerXPathNamespace('ns2', 'http://booking.us.org/');
$airlineName = $doc->xpath('//ns2:checkbalanceresponse/return/Balance/Airline/AirlineName')[0];
echo $airlineName;

Update: full code - as per question...

<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );

include_once("simple_html_dom.php");
$response = <<< XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<s:envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
      <s:body>
           <ns2:checkbalanceresponse xmlns:ns2="http://booking.us.org/">
                <return>
                     "<Balance><Airline><AirlineName>BUDDHA AIR</AirlineName><AgencyName>GANDAKI INTERNATIONAL TRAVELS KTM(STO)</AgencyName><BalanceAmount>5555</BalanceAmount></Airline></Balance>"
                 </return>
            </ns2:checkbalanceresponse>
       </s:body>
 </s:envelope>
XML;

$doc = simplexml_load_string($response);
$doc->registerXPathNamespace('ns2', 'http://booking.us.org/');
$airlineName = $doc->xpath('//ns2:checkbalanceresponse/return/Balance/Airline/AirlineName')[0];
echo $airlineName;

outputs...

BUDDHA AIR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM