dongzhuo3376 2018-10-01 18:59
浏览 114
已采纳

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

I have a file where I store comments. The file name is 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>

To loop through the XML tree, I am using the example given at W3Schools (with some modifications to the parameters). The code is contained in 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>";
  }
?>

As per the example, I am expecting:

User4251, 02.10.2018, Comment body goes here
User8650, 02.10.2018, Comment body goes here

However, I am getting three errors:

Warning: simplexml_load_file(): comments.xml:7: parser error : Extra content at the end of the document in 192.168.0.1/users/User8650/index.php on line 2

Warning: simplexml_load_file(): in 192.168.0.1/users/User8650/index.php on line 2

Warning: simplexml_load_file(): ^ in 192.168.0.1/users/User8650/index.php on line 2

Error: Cannot create object

The fourth one is due to the die() statement.

Is the example erroneous or am I going wrong somewhere?

  • 写回答

1条回答 默认 最新

  • duanjiu6697 2018-10-01 19:02
    关注

    You don't have a valid root element in your XML document. This will work:

    <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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。