我正在使用用作「數據庫」的XML文件。在這個例子中它擁有關於書籍的信息。使用simpleXML對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輸出進行排序,讓我們來說一下對象屬性「價格」。
<?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的順序,這有可能嗎?
我認爲xpath是更好的解決方案,謝謝。 – BoazKG 2015-02-25 04:40:10