PHP 中的 SimpleXML 處理
了解和 PHP 版本 5 捆綁到一起的 SimpleXML 擴展,它使 PHP 頁面能夠以 PHP 友好的語法來查詢、搜索、修改和重新發布 XML。
PHP 版本 5 引入了 SimpleXML,一種用于讀寫 XML 的新的應用程序編程接口(API)。在 SimpleXML 中,下面的這樣的表達式:
$doc->rss->channel->item->title
從文檔中選擇元素。只要熟悉文檔的結構,很容易編寫這種表達式。但是,如果不很清楚需要的元素出現在何處(比如 Docbook、HTML 和類似的敘述性文檔中),SimpleXML 可以使用 XPath 表達式尋找這些元素。
開始使用 SimpleXML
假設需要一個 PHP 頁面將 RSS 提要(feed)轉化成 HTML。RSS 是一種簡單的 XML 格式用于發布連鎖內容。文檔的根元素是 rss,它包括一個 channel 元素。channel 元素包含關于提要的元數據,如標題、語言和 URL。它還包含各種封裝在 item 元素中的報道。每個 item 都有一個 link 元素,包括一個 URL,還有 title 或 description(通常兩者都有),包含普通文本。不使用名稱空間。RSS 的內容當然不止這些,不過對本文來說知道這些就足夠了。清單 1 顯示了一個典型的例子,它包含兩個新聞項。
清單 1. RSS 提要
<?xml version='1.0' encoding='UTF-8'?><rss version='0.92'><channel> <title>Mokka mit Schlag</title> <link>http://www.elharo.com/blog</link> <language>en</language> <item> <title>Penn Station: Gone but not Forgotten</title> <description> The old Penn Station in New York was torn down before I was born. Looking at these pictures, that feels like a mistake.; The current site is functional, but no more; really just some office towers and underground corridors of no particular interest or beauty. The new Madison Square... </description> <link>http://www.elharo.com/blog/new-york/2006/07/31/penn-station</link> </item> <item> <title>Personal for Elliotte Harold</title> <description>Some people use very obnoxious spam filters that require you to type some random string in your subject such as E37T to get through. Needless to say neither I nor most other people bother to communicate with these paranoids. They are grossly overreacting to the spam problem. Personally I won't ...</description>
<link>http://www.elharo.com/blog/tech/2006/07/28/personal-for-elliotte-harold/</link> </item></channel></rss>
我們來開發一個 PHP 頁面將 RSS 提要格式化為 HTML。清單 2 顯示了這個頁面的基本結構。
清單 2. PHP 代碼的靜態結構
<?php // Load and parse the XML document ?><html xml:lang='en' lang='en'><head> <title><?php // The title will be read from the RSS ?></title></head><body>
<h1><?php // The title will be read from the RSS again ?></h1>
<?php// Here we'll put a loop to include each item's title and description?>
</body></html>
解析 XML 文檔
第一步是解析 XML 文檔并保存到變量中。只需要一行代碼,向 simplexml_load_file() 函數傳遞一個 URL 即可:
$rss = simplexml_load_file('http://partners.userland.com/nytRss/nytHomepage.xml');
對于這個例子,我已經從 Userland 的 New York Times 提要(在 http://partners.userland.com/nytRss/nytHomepage.xml)填充了頁面。當然,也可使用其他 RSS 提要的任何 URL。
要注意,雖然名稱為 simplexml_load_file(),該函數實際上解析遠程 HTTP URL 上的 XML 文檔。但這并不是該函數唯一令人感到奇怪的地方。返回值(這里存儲在 $rss 變量中)并沒有指向整個文檔,如果使用過其他 API 如文檔對象模型(DOM)您可能會這樣期望。相反,它指向文檔的根元素。從 SimpleXML 不能訪問文檔序言和結語部分的內容。
尋找提要標題
整個提要的標題(不是提要中各報道的標題)位于 rss 根元素 channel 的 title 孩子中。很容易找到這個標題,就仿佛 XML 文檔是類 rss 的一個對象的序列化形式,它的 channel 字段本身帶有一個 title 字段。使用常規 PHP 對象引用語法,尋找標題的語句如下:
$title = $rss->channel->title;
找到之后可以將其添加到輸出 HTML 中。這樣做很簡單,只要回顯 $title 變量即可:
<title><?php echo $title; ?></title>
這一行輸出元素的字符串值而不是整個元素。就是說寫入文本內容但不包括標簽。
甚至可以完全跳過中間變量 $title:
<title><?php echo $rss->channel->title; ?></title>
因為該頁面在多處重用這個值,我發現用一個含義明確的變量來存儲會更方便。
……
