PHP中的SimpleXML處理

來源:互聯網
上載者:User

簡介:瞭解和 PHP 版本 5 捆綁到一起的 SimpleXML 擴充,它使 PHP 頁面能夠以 PHP 友好的文法來 查詢、搜尋、修改和重新發布 XML。

PHP 版本 5 引入了 SimpleXML,一種用於讀寫 XML 的新的API(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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.