我正在使用simplexml来解析curl响应。我正确地得到了回复,但无法从响应中获取某些属性......
//Sending my data to web service
$curl = curl_init();
curl_setopt_array($curl, Array(
CURLOPT_URL => 'https://webservice.tld',
CURLOPT_POST => count($xml->asXML()),
CURLOPT_POSTFIELDS => $xml->asXML(),
CURLOPT_TIMEOUT => 120,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_ENCODING => 'UTF-8'
));
//Get the response
$reply = curl_exec($curl);
$responseData = simplexml_load_string($reply);
//Print the response
print_r($responseData);
然后将xml响应正确显示为:
<?xml version="1.0" encoding="utf-16"?>
<cXML payloadID="test" xml:lang="en" timestamp="2017-09-13T09:49:58.1219095+01:00">
<Response>
<Status code="500" text="Price does not match current pricelist" />
</Response>
</cXML>
但是,我正试图从状态中获取代码和文本属性,但它没有输出任何内容;
echo $responseData->Response->Status['code'] .' - '. $responseData->Response->Status['text'];
我也试过了;
echo $responseData->cXML->Response->Status['code'] .' - '. $responseData->cXML->Response->Status['text'];
想知道是否有人可以提供帮助?
感谢。
答案 0 :(得分:0)
你可以这样做。
foreach($responseData->Response->Status->attributes() as $key => $val){
echo $key .'='. $val;
}
这就是你可以阅读它的php文档here
答案 1 :(得分:0)
你得到的问题(这就是为调试设置错误消息的原因)是......
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$reply = <<< XML
<?xml version="1.0" encoding="utf-16"?>
<cXML payloadID="test" xml:lang="en" timestamp="2017-09-13T09:49:58.1219095+01:00">
<Response>
<Status code="500" text="Price does not match current pricelist" />
</Response>
</cXML>
XML;
$responseData = simplexml_load_string($reply);
...给出
Warning: simplexml_load_string(): Entity: line 1: parser error : Document labelled UTF-16 but has UTF-8 content in /home/nigel/workspace/PHPTest/TestSource/t1.php on line 15
如果您将utf-16更改为utf-8,那么这将解析确定,您的原始代码应该可以正常工作。
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$reply = <<< XML
<?xml version="1.0" encoding="utf-16"?>
<cXML payloadID="test" xml:lang="en" timestamp="2017-09-13T09:49:58.1219095+01:00">
<Response>
<Status code="500" text="Price does not match current pricelist" />
</Response>
</cXML>
XML;
$reply = preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $reply);
$responseData = simplexml_load_string($reply);
//Print the response
echo $responseData->Response->Status['code'];
如果生成XML的人修复了这个问题,那将是理想的,但是现在这将有助于解决问题。