我是xml的新手。我有来自api的字符串响应:
<PPResponse Result="000" Key="110308f9-6b67-422b-9dee-9c9da77d8197">
<ResultMessage>Operation is succesfully completed</ResultMessage>
<UtilityInfo>
<UtilityCode>123</UtilityCode>
</UtilityInfo>
<BillInfo>
<Bill>
<BillNumber>110308f9-6b67-422b-9d13-1c9da77d8197</BillNumber>
<DueDate>2015-12-10T07:31:44</DueDate>
<Amount>100</Amount>
<ReserveInfo>test</ReserveInfo>
<BillParam>
<mask>4</mask>
<commission type="0" val="0.00" op="-" paysource="1" />
</BillParam>
<RefStan>123123123123</RefStan>
</Bill>
</BillInfo>
</PPResponse>
我尝试将其转换为xml对象,如下所示:
`
libxml_use_internal_errors(true);
$simple_xml = simplexml_load_string($response);
if ($simple_xml === false) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
echo 'hi'; exit();
}
echo 'pass'; exit();`
显示通过。现在,错误是,当我dd($ simple_xml)时,我什么也得不到:
libxml_use_internal_errors(true);
$simple_xml = simplexml_load_string($response);
if ($simple_xml === false) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
echo 'hi'; exit();
}
dd($simple_xml)
我需要在将其转换为xml对象后访问字符串中的键和值。我认为,正则表达式也是解决方案,但我需要通过xml对象。
任何帮助都将受到高度赞赏。这是一种紧急情况。
答案 0 :(得分:0)
这对我来说很好用:
libxml_use_internal_errors(true);
$xml = simplexml_load_string($response);
// var_dump($xml); this will output the xml object just fine
if ($xml !== false) {
echo "Successfuly loaded the XML" . PHP_EOL;
print "Message: " . $xml->ResultMessage . PHP_EOL;
print "Utility code: " . $xml->UtilityInfo->UtilityCode . PHP_EOL;
print "Bill Amount: " . $xml->BillInfo->Bill->Amount . PHP_EOL;
}
else{
echo "Failed loading the XML" . PHP_EOL;
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
将显示
Successfuly loaded the XML
Message: Operation is succesfully completed
Utility code: 78
Bill Amount: 0
使用以下代码测试BOM序列,如果存在则将其删除
$bom = pack("CCC", 0xef, 0xbb, 0xbf);
if (0 === strncmp($response, $bom, 3)) {
echo "BOM detected - file is UTF-8" . PHP_EOL;
$response = substr($response, 3);
}
// or
$response = str_replace("\xEF\xBB\xBF",'',$reponse);