我正在使用下面的脚本将输入字段中的文本添加到 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>
最佳答案
这里是带有答案的类似问题的链接
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());
}
关于PHP addChild 到列表顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8146039/