Welcome 微信登录

首页 / 网页编程 / PHP / PHP中的SimpleXML处理

PHP中的SimpleXML处理2011-09-19 IBM Elliotte Harold简介:了解和 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>