Reputation: 1883
I tried below code to extract data from below XML but got an empty string.
<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>
$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
Upvotes: 1
Views: 57
Reputation: 57121
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
Upvotes: 0
Reputation: 15141
You can do it like this.
Problem:
$nodes[0]->return;
This statement will return an object instead of string.
$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;
Upvotes: 1