PHP - simplexml_load_string没有按预期工作

时间:2016-10-18 03:34:04

标签: php simplexml-load-string

将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的数组。

1 个答案:

答案 0 :(得分:1)

在此上下文中,print_recho之间存在差异。而是打印尝试回声

echo (string) $result->title;

它将作为SMART

工作和输出

和数组

$p = 1;
foreach ($result->documents as $value) {
  echo $value->name . "<br/>";
  //for key
  echo $p++.'</br>';
}
相关问题