将xml转换为对象时,根据print_r($result);
,一切似乎都很好。但是如果我使用$result->title
它返回对象而不是字符串,当循环$result->documents
时,它变得非常奇怪..
$xml = '<return>
<id>65510</id>
<title>SMART</title>
<info/>
<documents>
<name>file_1.pdf</name>
<path>http://www.domain.com/documents/file_1.pdf</path>
</documents>
<documents>
<name>file_2.pdf</name>
<path>http://www.domain.com/documents/file_2.pdf</path>
</documents>
<documents>
<name>file_3.pdf</name>
<path>http://www.domain.com/documents/file_3.pdf</path>
</documents>
</return>';
$result = simplexml_load_string($xml);
print_r($result); /* returns:
SimpleXMLElement Object
(
[id] => 65510
[title] => SMART
[info] => SimpleXMLElement Object
(
)
[documents] => Array
(
[0] => SimpleXMLElement Object
(
[name] => file_1.pdf
[path] => http://www.domain.com/documents/file_1.pdf
)
[1] => SimpleXMLElement Object
(
[name] => file_2.pdf
[path] => http://www.domain.com/documents/file_2.pdf
)
[2] => SimpleXMLElement Object
(
[name] => file_3.pdf
[path] => http://www.domain.com/documents/file_3.pdf
)
)
)
*/
$_VALUE['title'] = $result->title;
print_r($_VALUE); /* returns:
Array
(
[title] => SimpleXMLElement Object
(
[0] => SMART
)
)
*/
foreach ($result->documents as $key=>$value) {
echo $key . "<br/>";
} /* returns:
documents
documents
documents
instead of returning:
1
2
3
*/
我需要$result->title
返回字符串,$result->documents
是一个索引为1,2,3的数组。
答案 0 :(得分:1)
在此上下文中,print_r
和echo
之间存在差异。而是打印尝试回声
echo (string) $result->title;
它将作为SMART
和数组
$p = 1;
foreach ($result->documents as $value) {
echo $value->name . "<br/>";
//for key
echo $p++.'</br>';
}