Parsing xml data in an order using xquery
I have a xml file like this
<?xml version="1.0" encoding="UTF-8"?>
<gallery >
<gallerydata>
<galleryname>
Home
</galleryname>
<createdat>
14/8/2010 4:53 pm
</createdat>
</gallerydata>
<gallerydata>
<galleryname>
School
</galleryname>
<createdat>
13/8/2010 5:19 pm
</createdat>
</gallerydata>
开发者_开发技巧 <gallerydata>
<galleryname>
Company
</galleryname>
<createdat>
15/8/2010 5:21 pm
</createdat>
</gallerydata>
</gallery>
Iam using xpath and xquery for parsing this xml file
$xml_str = file_get_contents($file);
$xml = simplexml_load_string($xml_str);
$nodes = $xml->xpath('//gallery/gallerydata');
How i can get the latest gallery data, i mean latest file (the data with last date )
Is their any way to do ?Please help me
IF you looking for a way to do it with the initial xpath query that could be rough, i dont think xpath 1.0 can parse dates so youd have to do some convoluted string comparison... If youre ok with doing it in php after the fact theres a multitude of ways... for example:
$xml = new SimpleXmlElement($xmlStr);
$gallerydata = $xml->xpath('//gallerydata');
$nodes = array();
foreach($gallerydata as $entry)
{
$utime = strtotime(str_replace('/', '-',$entry->createdat));
$nodes[$utime] = $entry;
}
krsort($nodes);
$newest = array_shift($nodes);
echo $newest->asXml(); // or do wht you need to do with the entry data...
This loops over your renturned node set and puts the nodes in an array indexed by unix time. Then I run a reversed key sort and shift the first element off the array. Note, that since im using strtotime
for the conversion and you have UK date formats we have to do a string replace on the slashes.
Since your file does not store gallery data in chronological order, you can get the latest gallery entry only by looping through all the entries.
精彩评论