使用简单的XML和xpath对表字段进行排序 [英] sorting the table fields using simple XML and xpath

查看:129
本文介绍了使用简单的XML和xpath对表字段进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个加载了simplexml的xml文件,我需要按价格,作者或标题对字段进行排序.我该怎么办?可以使用xpath或其他方式吗?我在这里看到了类似的示例,但我不太清楚

I have a xml file loaded simplexml, and I need to sort the fields by price, or by author or title. How could I do? Is it ok do it using xpath or another way? I saw a similar example here, but I have not very clear

XML

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <libro>
        <autor><![CDATA[Cervantes]]></autor>
        <titulo><![CDATA[El Quijote]]></titulo>
        <precio>30€</precio>
    </libro>
    <libro>
        <autor><![CDATA[Calderón de la Barca]]></autor>
        <titulo><![CDATA[La vida es sueño]]></titulo>
        <precio>25€</precio>
    </libro>
    <libro>
        <autor><![CDATA[Garcilaso de la vega]]></autor>
        <titulo><![CDATA[Egoglas]]></titulo>
        <precio>15€</precio>
    </libro>
    <libro>
        <autor><![CDATA[Raymond Carver]]></autor>
        <titulo><![CDATA[Catedral]]></titulo>
        <precio>16€</precio>
    </libro>
    <libro>
        <autor><![CDATA[George Orwell]]></autor>
        <titulo><![CDATA[1984]]></titulo>
        <precio>10€</precio>
    </libro>
    <libro>
        <autor><![CDATA[Fidor Dostoyevski]]></autor>
        <titulo><![CDATA[Crimen y Castigo]]></titulo>
        <precio>35€</precio>
    </libro>
    <libro>
        <autor><![CDATA[Juan Ponce]]></autor>
        <titulo><![CDATA[Cronica de la intervencion]]></titulo>
        <precio>25€</precio>
    </libro>
    <libro>
        <autor><![CDATA[Yukio Mishima]]></autor>
        <titulo><![CDATA[Confesiones de una mascara]]></titulo>
        <precio>22€</precio>
    </libro>
    <libro>
        <autor><![CDATA[Elfriede Jelinek]]></autor>
        <titulo><![CDATA[Deseo]]></titulo>
        <precio>20€</precio>
    </libro>
    <libro>
        <autor><![CDATA[Bram Stoker]]></autor>
        <titulo><![CDATA[Dracula]]></titulo>
        <precio>18€</precio>
    </libro>
</root>

PHP

$xml = simplexml_load_file('xml/libros.xml');
$sum = 0;
$h = "<table>";
$h .= "<tr>";
$h .= "<td><a href='#'  id='ordAut'><img src='img/up_down.png' /></a></td><td><a href='#'  id='ordTit'><img src='img/up_down.png' /></a></td><td><a href='#'  id='ordPre'><img src='img/up_down.png' /></a></td>";
$h .= "</tr>";
foreach ($xml->libro as $book) {
    $h .= "<tr>";
    $h .= "<td>".$book->autor."</td><td>".$book->titulo."</td><td>".$book->precio."</td>";
    $h .= "</tr>";
    $sum += $book->precio;
}

$h .= "<tr><td colspan=\"2\">sum:</td><td>$sum</td></tr></table>";
echo $h;

推荐答案

像这样对您的simplexml进行排序:

Sort your simplexml like this:

功能sort_obj_arr

实时演示@ http://codepad.viper-7.com/QvLqIq

这篇关于使用简单的XML和xpath对表字段进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆