使用 simpleXML 对 xml 输出的顺序进行排序

Sort the order of an xml output using simpleXML

我正在处理用作 "database" 的 XML 文件。在此示例中,它包含有关书籍的信息。

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology 
      society in England, the young survivors lay the 
      foundation for a new society.</description>
   </book>
</catalog>

然后我想在我的页面上显示这本书的价格,使用简单XML。 但是我的客户要求一个 "sort by" 按钮。我在 Google 中找不到任何方法来对简单的 XML 输出进行排序,比如说对象 属性 "price".

<?php 

$xml = simplexml_load_file('example.xml');
$number = count($xml->book);        
        //Looping through the xml.
        for($i = 0; $i < $number; $i++) {   ?>
            <div class="info">
                <span><?php echo((string) $xml->book[$i]->price); ?></span>
            </div>
    <?php } ?>

就像现在一样,它只是按照 xml 中的顺序显示这本书的价格。 我想也许可以使用 JS 来进行此操作,但似乎不太可能,因为这意味着我必须将所有书籍放在一页中。我什至想过使用 SQL 然后使用 ORDER BY 子句,但问题是这个 XML 是动态的并且一直在变化,这意味着我需要始终注意 XML 文件并自动更新 SQL 数据库,我还不知道该怎么做。我真正想要的是使用 PHP 改变 XML 的顺序,这可能吗?

直接是不可能的。您必须从 xml 构建一个数组,对该数组进行排序,然后重新构建 xml。创建 2 个数组,一个用于保留 xml 段,其中索引是 book_id,值是段。第二个仅以图书 ID 作为键,并作为要使用 asort 排序的字段的值。对第二个数组进行排序并重建 xml.

==更新==

也许可以使用 xPath 和 XSL 对 xml 进行排序,这里有一个 link.