无法在 PHP 中遍历 XML 节点 [英] Cannot loop through XML nodes in PHP
问题描述
我有一个用于存储评论的文件.文件名为 comments.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>
为了遍历 XML 树,我使用了 W3Schools 中给出的示例(对参数进行了一些修改).代码包含在 index.php 中:
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>";
}
?>
根据示例,我期待:
User4251, 02.10.2018, Comment body goes here
User8650, 02.10.2018, Comment body goes here
但是,我收到三个错误:
However, I am getting three errors:
警告: simplexml_load_file():comments.xml:7:解析器错误:192.168.0.1/users/User8650/index.php中文档末尾的额外内容强>在线2
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
警告: simplexml_load_file():在 192.168.0.1/users/User8650/index.php 中 2
Warning: simplexml_load_file(): in 192.168.0.1/users/User8650/index.php on line 2
警告: simplexml_load_file(): ^ in 192.168.0.1/users/User8650/index.php 2
Warning: simplexml_load_file(): ^ in 192.168.0.1/users/User8650/index.php on line 2
错误:无法创建对象
第四个是由于 die()
语句.
The fourth one is due to the die()
statement.
这个例子是错误的还是我哪里出错了?
Is the example erroneous or am I going wrong somewhere?
推荐答案
您没有有效的 XML 文档中的根元素.这将起作用:
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>
这篇关于无法在 PHP 中遍历 XML 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!