【问题标题】:PHP addChild to top of list?PHP addChild 到列表顶部?
【发布时间】:2011-11-16 02:47:01
【问题描述】:

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

【问题讨论】:

  • 不要相信你可以用simplexml指定插入位置。但是对于完整的 DOM,您可以使用 insertBefore() 在子列表顶部插入一个节点。
  • 那么 insertBefore() 会替换 addChild 吗?
  • 没有。 DOM 有 appendChild 用于在之后(或末尾)添加。它们都插入节点,但在不同的位置插入新节点。

标签: php html css xml


【解决方案1】:

这里是类似问题的链接和答案

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());
 }

【讨论】:

  • 好的,我明白你们现在的意思了。但由于某种原因,它不适用于我的情况。仍然在前一个下面添加孩子...
猜你喜欢
  • 2012-09-19
  • 1970-01-01
  • 2011-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-25
  • 2018-04-25
  • 1970-01-01
相关资源
最近更新 更多