程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> PHP 中的 SimpleXML 處理

PHP 中的 SimpleXML 處理

編輯:關於PHP編程

  了解和 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 wont ...</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>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved