跟进我的上一个问题。
我正在使用
addChild()
添加另一个 <comment>
元素作为根元素的子元素。我使用了this问题中的代码:
$file = "comments.xml";
$comment = $xml -> comment;
$comment -> addChild("user","User2245");
$comment -> addChild("date","02.10.2018");
$comment -> addChild("text","The comment text goes here");
$xml -> asXML($file)
现在,当我回显文件内容时:
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
我正在使用相同的 comments.xml 文件。没有显示任何错误。
为什么子元素没有被追加?
您要添加到
comment
元素之一,请将其添加到完整文档中。
$xml = new simplexmlelement('<?xml version="1.0" encoding="utf-8"?>
<comments><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></comments>');
$child = $xml->addchild('comment');
$child->addChild("user","User2245");
$child->addChild("date","02.10.2018");
$child->addChild("text","The comment text goes here");
echo $xml->asXML();
如果您使用
echo $xml->asXML()
输出完整的 XML,您将看到,按照您的请求,其他子节点已添加到第一个注释节点:
<comment>
<user>User4251</user>
<date>02.10.2018</date>
<text>Comment body goes here</text>
<user>User2245</user><date>02.10.2018</date><text>The comment text goes here</text>
</comment>
仅第一个
comment
已更改的原因与您的
echo
不显示新值的原因相同:如果您引用像
$xml->comment
或
$comment->user
这样的元素,您将获得first 子元素具有该名称的元素;它只是
$xml->comment[0]
或
$comment->user[0]
的简写。这对于浏览 XML 文档来说实际上非常方便,因为您不必知道是否有一个或多个具有特定名称的元素,您可以编写
$xml->comment->user
或
$xml->comment[0]->user[0]
或
$xml->comment->user[0]
等等。自从您调用
addChild
以来,新的
user
、
date
和
text
不是第一个使用该名称的子项,因此它们不会出现在您的输出中。如果您想要创建
新评论,您需要先添加:
$comment = $xml->addChild('comment');
$comment->addChild('user', 'User2245');
如果您想要
更改子元素的值,您可以直接写入它们,而不是添加新的子元素:
$comment = $xml->comment[0]; // or just $comment = $xml->comment;
$comment->user = 'User2245';
或者您可以向现有注释中的
每个添加一些内容(请注意,这里我们使用 $xml->comment
,就好像它是一个数组一样;同样,无论有一个还是多个匹配元素,SimpleXML 都会让我们这样做):
foreach ( $xml->comment as $comment ) {
$comment->addChild('modified', 'true');
}