PHP - simplexml_load_string不能按预期方式工作

问题描述:

将xml转换为对象时,根据print_r($result);,一切看起来都正常。但是,如果使用$result->title它返回对象,而不是字符串和循环$result->documents它变得非常奇怪..PHP - simplexml_load_string不能按预期方式工作

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

在此背景下,print_recho之间有区别。相反,打印尝试呼应

echo (string) $result->title; 

它将工作和输出SMART

和阵列

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

好,但我在PHPMailer的使用这些值,它会抛出错误:致命错误:未捕获的异常'异常'与'消息''SimpleXMLElement序列化'是不允许' – Totallama

+0

好吧,那么你必须键入case数据作为'字符串',因为它们在内部都是'SimpleXMLElement'.So它应该像'echo(string)$ result-> title ;' –

+0

又是什么回合阵列? – Totallama