交替出现错误(文档末尾的额外内容) [英] Alternately getting the error (Extra content at the end of the document )
问题描述
我在加载 xml 文件时出错.我得到了许多与该主题相关的答案,但我真的找不到为什么我的文件中可能会出现此错误.
I am getting error while loading the xml file. I got many answers related to the topic but I really could not find why this error maybe coming in my file.
Warning: DOMDocument::load() [<a href='domdocument.load'>domdocument.load</a>]: Extra content at the end of the document
当我运行文件时,它运行成功,但是当我重新加载它时,它给出了上述错误而不是添加另一个节点.但是,下次当我重新加载它时,它会再次成功运行.这是交替发生的.请有人告诉我为什么会发生这种情况以及如何解决问题.
When I am running the file, it runs successfully, but when I reload it, it gives the above error instead of adding another node. But, next time when I reload it runs successfully again. This is happening alternatively. Please someone tell me why is this happening and how to solve the problem.
我正在使用这个 php 代码来编辑 xml 文件:
I am using this php code to edit the xml file:
<?php
$dom = new DomDocument("1.0", "UTF-8");
$dom->load('filename.xml');
$noteElem = $dom->createElement('note');
$toElem = $dom->createElement('to', 'Chikck');
$fromElem = $dom->createElement('from', 'ewrw');
$noteElem->appendChild($toElem);
$noteElem->appendChild($fromElem);
$dom->appendChild($noteElem);
$dom->formatOutput = TRUE;
//$xmlString = $dom->saveXML();
//echo $xmlString;
$dom->save('filename.xml');
?>
这是我正在编辑的 xml 文件:
This is the xml file I am editing:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Chikck</to>
<from>ewrw</from>
</note>
推荐答案
额外的内容错误是由于将两个相同的节点(在本例中为 note
节点)作为根元素引起的.
The extra content error is caused by having two of the same node, in this case the note
node, as a root element.
例如,您可以添加一个新的根元素 notes
,然后在其中添加更多 note
元素.
You could add a new root element notes
for example, and then add more note
elements within that.
这里有一个使用 simplexml 库的例子(只是因为我使用了这个并且我很熟悉它)
Here's an example using the simplexml library (just because I use this one and I'm familiar with it)
新的 filename2.xml:(添加了 notes
元素作为根)
New filename2.xml: (with added notes
element as root)
<?xml version="1.0" encoding="UTF-8"?>
<notes>
<note>
<to>Chikck</to>
<from>ewrw</from>
</note>
</notes>
PHP 脚本:
<?php
$xml = simplexml_load_file('filename2.xml');
$note = $xml->addChild('note');
$to = $note->addchild('to', 'Chikck');
$from = $note->addChild('from', 'ewrw');
$xml->asXML('filename2.xml');
?>
运行脚本后的filename2.xml:
filename2.xml after running script:
<?xml version="1.0" encoding="UTF-8"?>
<notes>
<note>
<to>Chikck</to>
<from>ewrw</from>
</note>
<note>
<to>Chikck</to>
<from>ewrw</from>
</note>
</notes>
这篇关于交替出现错误(文档末尾的额外内容)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!