在响应中,我们收到一个xml文件,然后转换为SimpleXMLElement,然后根据需要访问元素和属性。然而,当直接从字符串响应加载xml时,与从保存的响应加载xml相比,我们得到的是"尝试获取非对象的属性"。
//This code works
$response = simplexml_load_file( "response.xml" );
var_dump($response);
echo $response->RESPONSE->RESPONSE_DATA->FILE_INFORMATION['Order_Number'];
//Returns
//object(SimpleXMLElement)#153 (4) { ["@attributes"]=> array(1)...the rest of the xml file...
//Order_Number
//This code returns error
$response = simplexml_load_string( $response );
var_dump($response);
echo $response->RESPONSE->RESPONSE_DATA->FILE_INFORMATION['Order_Number'];
//Returns
//object(SimpleXMLElement)#153 (1) { [0]=> string(33864) "" }
//Notice: Trying to get property of non-object in...
当使用simplexml_load_string而不是simplexml_lad_file时,是什么导致xml失败?
以下是xml文件的一个片段:
<?xml version="1.0" encoding="UTF-8"?>
<RESPONSE_GROUP>
<RESPONSE>
<RESPONSE_DATA>
<FILE_INFORMATION Order_Number="19222835">
...
</FILE_INFORMATION>
</RESPONSE_DATA>
</RESPONSE>
</RESPONSE_GROUP>
您刚才忽略了一个小细节。你对第一部分所说的是正确的:
$response = simplexml_load_file( "response.xml" );
这将从文件中加载XML文档。然而,当你看第二部分时:
$response = simplexml_load_string( $response );
您不从字符串响应加载。$response
表示您刚刚从文件中创建的SimpleXMLElement。更"正确"的例子是:
$buffer = file_get_contents( "response.xml" );
$response = simplexml_load_string( $buffer );
您可能只是因为变量重用而感到困惑(对两个不同的事物使用相同名称的变量)。
与var_dump
一样,最好使用$response->asXML()
进行检查,因为它会将文档显示为XML,从而更好地显示您所拥有的(或没有)。
这对我有效:
<?php
$response = '<?xml version="1.0" encoding="UTF-8"?>
<RESPONSE_GROUP>
<RESPONSE>
<RESPONSE_DATA>
<FILE_INFORMATION Order_Number="19222835">
...
</FILE_INFORMATION>
</RESPONSE_DATA>
</RESPONSE>
</RESPONSE_GROUP>';
//This code returns error
$response = simplexml_load_string( $response );
var_dump($response);
echo $response->RESPONSE->RESPONSE_DATA->FILE_INFORMATION['Order_Number'];
?>
输出:
object(SimpleXMLElement)#1 (1) {
["RESPONSE"]=>
object(SimpleXMLElement)#2 (1) {
["RESPONSE_DATA"]=>
object(SimpleXMLElement)#3 (1) {
["FILE_INFORMATION"]=>
string(33) "
...
"
}
}
}
19222835