繁体   English   中英

使用命名空间从 XML 中提取数据

[英]Extract Data from XML with namespace

我尝试使用下面的代码从 XML 下方提取数据,但得到了一个空字符串。

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>

代码

 $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 

你可以这样做。

问题: $nodes[0]->return; 此语句将返回一个对象而不是字符串。

在此处尝试此代码片段

$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;

由于<return>内容已经是 XML,因此不必将其作为字符串读取然后进行转换,您的第一个 simplexml_load_string 已经完成了所有工作。 您可以直接从 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;

更新:完整代码 - 根据问题...

<?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;

输出...

BUDDHA AIR

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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