【问题标题】:Sort the order of an xml output using simpleXML使用 simpleXML 对 xml 输出的顺序进行排序
【发布时间】:2015-02-25 04:26:45
【问题描述】:

我正在处理用作“数据库”的 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>

然后我想在我的页面中显示这本书的价格,使用 simpleXML。 但我的客户要求提供“排序依据”按钮。我在 Google 和 SO 中找不到任何方法来对 simpleXML 输出进行排序,比如对象属性“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 的顺序,这可能吗?

【问题讨论】:

    标签: php xml sorting simplexml


    【解决方案1】:

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

    == 更新 ==

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

    【讨论】:

    • 我认为 xpath 是这里更好的解决方案,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2011-01-13
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2023-01-11
    相关资源
    最近更新 更多