Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have tried to get an XML file to sort and have had no luck. After a day and a-half, I need some help from an expert. Thanks.

My XML File (shortened for the example):

<?xml version="1.0" encoding="iso-8859-1"?>
<deadlines>
    <deadline>
        <date>2010-06-01</date>
        <text>Application for Summer Due</text>
    </deadline>
    <deadline>
        <date>2010-07-01</date>
        <text>Application for Fall Due</text>
    </deadline>
    <deadline>
        <date>2010-07-31</date>
        <text>Summer Bill Due</text>
    </deadline>
</deadlines>

My PHP:

<?php

$xml = simplexml_load_file($_SERVER['DOCUMENT_ROOT'].'/feeds/deadlines.xml');

// start THIS WORKS
echo'<pre>';
foreach($xml as $deadline) echo <<<EOF
    Date: {$deadline->date}
    Text: {$deadline->text}


EOF;
echo'</pre>';
// end THIS WORKS

?>

Does anyone have a simple PHP solution to sort the XML file on "date" prior to the echo to screen?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
256 views
Welcome To Ask or Share your Answers For Others

1 Answer

Okay, sorry for going around the houses before - I've added a different answer for clarity but using the sort proxying technique I linked to.

function xsort(&$nodes, $child_name, $order=SORT_ASC)
{
    $sort_proxy = array();

    foreach ($nodes as $k => $node) {
        $sort_proxy[$k] = (string) $node->$child_name;
    }

    array_multisort($sort_proxy, $order, $nodes);
}

$structure = '<?xml version="1.0" encoding="utf-8" ?>
<deadlines>
    <deadline>
        <date>2010-06-01</date>
        <text>Application for Summer Due</text>
    </deadline>
    <deadline>
        <date>2010-07-01</date>
        <text>Application for Fall Due</text>
    </deadline>
    <deadline>
        <date>2010-07-31</date>
        <text>Summer Bill Due</text>
    </deadline>
</deadlines>';

$xml = simplexml_load_string($structure);
$nodes = $xml->xpath('/deadlines/deadline');

// Sort by date, descending
xsort($nodes, 'date', SORT_DESC);
var_dump($nodes);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...