【问题标题】:PHP parse xml contentPHP解析xml内容
【发布时间】:2016-05-05 21:07:19
【问题描述】:

这就是我发送请求的方式

$header = "POST 213.207.000.000/services/AmountCharging/v3 HTTP/1.1 \r\n"; $header .= "Content-type: text/xml;charset=UTF-8 \r\n"; 
$header .= "Content-length: ".strlen($request_xml)." \r\n"; 
$header .= "Content-transfer-encoding: text \r\n"; 
$header .= "Connection: Keep-Alive \r\n\r\n"; 
$header .= $request_xml; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_TIMEOUT, 120); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);
$strxml = curl_exec($ch);  

下面是我的 XML 响应,使用 php 我只想获取 <soapenv:Body></soapenv:Body> 的内容

<?xml version="1.0" encoding="utf-8" ?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns1:chargeAmountResponse xmlns:ns1="http://www.csapi.org/schema/parlayx/payment/amount_charging/v3_1/local"></ns1:chargeAmountResponse>
</soapenv:Body>
</soapenv:Envelope>

有什么想法吗? 谢谢。。

【问题讨论】:

标签: php xml soap


【解决方案1】:

鉴于在 soapenv:Body 中确实没有什么值得一看的东西,以下内容并没有真正显示出任何有趣的东西,但应该会有所帮助。

$strxml='<?xml version="1.0" encoding="utf-8" ?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Body>
        <ns1:chargeAmountResponse xmlns:ns1="http://www.csapi.org/schema/parlayx/payment/amount_charging/v3_1/local"></ns1:chargeAmountResponse>
    </soapenv:Body>
</soapenv:Envelope>';

$dom=new DOMDocument;
$dom->loadXML( $strxml );
$body=$dom->getElementsByTagNameNS('http://schemas.xmlsoap.org/soap/envelope/','Body')->item(0);
echo 'Body: '.$body->tagName.', Child: '.$body->childNodes->item(1)->tagName.', Attribute: '.$body->childNodes->item(1)->getAttribute('xmlns:ns1');


Output
------
Body: soapenv:Body, Child: ns1:chargeAmountResponse, Attribute: http://www.csapi.org/schema/parlayx/payment/amount_charging/v3_1/local


update:
-------

Given that it does appear supplying a single line string causes errors
you could aproach it slightly differently.

$col=$dom->getElementsByTagName('*');
foreach( $col as $node ) {
    echo 'tag:'.$node->tagName.' value:'.$node->nodeValue.BR;   
}

【讨论】:

  • 对于 echo 行,我收到以下错误消息:-> 注意:尝试获取非对象的属性致命错误:调用成员函数 getAttribute()
  • RamRaider,当我把 $strxml 作为上面的例子时,你说它有效,但是当我将它合并到我的代码中时,从 $strxml= curl_exec($ch);没有,这是为什么呢?
  • 这取决于你的代码——没有看过代码很难说。
  • 请检查上面我已经添加了我的 curl 请求和处理代码。谢谢
  • 我注意到 $strxml = curl_exec($ch);是一行,它不适用于您提供的代码。如何使用折线将其转换为 XML 标准格式?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多