简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM