PHP addChild 到列表顶部?

标签 php html css xml

我正在使用下面的脚本将输入字段中的文本添加到 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/

相关文章:

php - Symfony2 和 1969/04/27 日期

php - bool 搜索运算符优化,尊重引用的术语

php - 为什么在 Laravel 中对 Request 对象和 request() 助手使用依赖注入(inject)?

html - 使用媒体查询为 Retina Display 用户显示高分辨率 Logo ?

html - 包含图像的 block anchor 从容器 div 溢出

php - 尝试从 azure blob 下载文件,mime 类型有问题

html - 如何在 li 中显示内联输入?

css - GitHub 页面仅显示 html,来自具有 CSS 文件夹的网站存储库

javascript - 如何在将鼠标悬停在图像上时弹出 youtube 视频播放器

javascript - "overflow-wrap:break-word"的浏览器兼容性