0

I'm trying to add a comment list to a page using an xml file. I'd like to list the comments most recent first, so when a new comment is added, I'd like to add it to the start of the xml. addChild appends to the end, so that's no good, and I can't get my head around the the DOMNode insert_before method, as I want to add it at the start before every other occurrence of a child (and I can't find an example anywhere that does this - weird).

xml file looks like;

<comments>
    <comment>
        <date>20130625</date>
        <name>Jocky Wilson</name>
        <text>Something about darts presumably</text>
    </comment>
    <comment>
        <date>20130622</date>
        <name>Jacky Wilson</name>
        <text>It was reet petite etc</text>
    </comment>
</comments>

I create the file initially with;

<?php
    $xmlData = "< load of xml etc...";
    $xml = new SimpleXMLElement($xmlData);
    file_put_contents("comments.xml", $xml->asXML());
?>

And that works fine. Any suggestions at all gratefully received.

Ian
  • 3
  • 2
  • maybe this will help you http://stackoverflow.com/questions/3361036/php-simplexml-insert-node-at-certain-position – Robert Jun 25 '13 at 12:04
  • Take a look at this question, there is a pretty nice solution ;) http://stackoverflow.com/a/2093059/2519566 – Avinor Jun 25 '13 at 13:15

1 Answers1

0

As an alternative to the solutions mentioned in the comments:
use addChild, let it add the node wherever it wants to, sort it by <date> and echo it:

$xml = simplexml_load_string($x); // assume XML in $x
$comments = $xml->xpath("//comment");

$field = 'date';
sort_obj_arr($comments, $field, SORT_DESC);

var_dump($comments);


// function sort_obj_array written by GZipp, see link below
function sort_obj_arr(& $arr, $sort_field, $sort_direction) {
    $sort_func = function($obj_1, $obj_2) use ($sort_field, $sort_direction) {
        if ($sort_direction == SORT_ASC) {
            return strnatcasecmp($obj_1->$sort_field, $obj_2->$sort_field);
        } else {
            return strnatcasecmp($obj_2->$sort_field, $obj_1->$sort_field);
        }
    };
    usort($arr, $sort_func);
} 

see GZipp's original function: Sorting an array of SimpleXML objects

Community
  • 1
  • 1
michi
  • 6,565
  • 4
  • 33
  • 56