我正在使用下面的脚本将输入字段中的文本添加到XML文件中。我对在列表的顶部添加一个项目感到困惑,也许是firstChild?因为每当PHP发布来自输入字段的文本时,它都会将其添加到XML树的底部,有必要让它成为树上的第一项吗?
<?php
if ($_POST['post']) {
$xml = simplexml_load_file('feed.xml');
$item = $xml->channel->addChild('item');
$item->addChild('title', htmlspecialchars($_POST['post']));
file_put_contents('feed.xml', $xml->asXML());
}
?>下面是我想要的XML的样子。
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<item>
<title>Item 3</title>
</item>
<item>
<title>Item 2</title>
</item>
<item>
<title>Item 1</title>
</item>
</channel>
</rss>发布于 2011-11-16 11:38:02
这里有一个类似问题的链接和答案
How to prepend a child in Simple XML
class my_node extends SimpleXMLElement
{
public function prependChild($name)
{
$dom = dom_import_simplexml($this);
$new = $dom->insertBefore(
$dom->ownerDocument->createElement($name),
$dom->firstChild
);
return simplexml_import_dom($new, get_class($this));
}
}
if ($_POST['post']) {
$xml = simplexml_load_file('feed.xml');
$item = $xml->channel->prependChild('item');
$item->addChild('title', htmlspecialchars($_POST['post']));
file_put_contents('feed.xml', $xml->asXML());
}https://stackoverflow.com/questions/8146039
复制相似问题