0

I'm working with this script below to add text from an input field to an XML file. I'm confused on adding a an item to the top of list, maybe firstChild? Because when ever the PHP posts the text from the input field it adds it to the bottom of the XML tree, is there anyway to have it be the first item on the tree?

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

Here's what I want the XML to look like.

<?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>
  • Don't believe you can specify an insert location with simplexml. But with the full DOM, you can use `insertBefore()` to insert a node at the top of the children list. – Marc B Nov 16 '11 at 03:32
  • Would insertBefore() replace addChild then? –  Nov 16 '11 at 03:34
  • No. DOM has appendChild for adding after (or at the end). They both insert nodes, but insert the new node in different locations. – Marc B Nov 16 '11 at 03:37

1 Answers1

0

Here the the link for a similar question with the answer

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());
 }
Community
  • 1
  • 1
Dev Jadeja
  • 130
  • 1
  • 9
  • Okay, I see what you guys mean now. But it's not working in my situation for some reason. Still adds the child below the previous one... –  Nov 16 '11 at 03:41