无法在PHP中循环遍历XML节点

Wai*_*mal 1 php xml

我有一个存储评论的文件.文件名是comments.xml:

<?xml version="1.0" encoding="utf-8"?>
<comment>
  <user>User4251</user>
  <date>02.10.2018</date>
  <text>Comment body goes here</text>
</comment>
<comment>
  <user>User8650</user>
  <date>01.10.2018</date>
  <text>Comment body goes here</text>
</comment>
Run Code Online (Sandbox Code Playgroud)

为了遍历XML树,我使用W3Schools给出的示例(对参数进行了一些修改).代码包含在index.php中:

<?php
  $xml = simplexml_load_file("comments.xml") or die("Error: Cannot create object");
  foreach($xml -> children() as $comments) { 
    echo $comments -> user . ", "; 
    echo $comments -> date . ", "; 
    echo $comments -> text . "<br>";
  }
?>
Run Code Online (Sandbox Code Playgroud)

根据这个例子,我期待:

User4251, 02.10.2018, Comment body goes here
User8650, 02.10.2018, Comment body goes here
Run Code Online (Sandbox Code Playgroud)

但是,我收到三个错误:

警告: simplexml_load_file():comments.xml:7:解析器错误:第2行的192.168.0.1/users/User8650/index.php文档末尾的额外内容

警告: simplexml_load_file():在第2行的192.168.0.1/users/User8650/index.php中

警告: simplexml_load_file():^在第2行的192.168.0.1/users/User8650/index.php中

错误:无法创建对象

第四个是由于die()声明.

这个例子是错误的还是我在某个地方出错了?

may*_*ign 5

您的XML文档中没有有效的根元素.这将有效:

<root_example>
 <comment>
   <user>User4251</user>
   <date>02.10.2018</date>
   <text>Comment body goes here</text>
  </comment>
  <comment>
   <user>User8650</user>
   <date>01.10.2018</date>
   <text>Comment body goes here</text>
 </comment>
</root_example>
Run Code Online (Sandbox Code Playgroud)