simpleXML 解析xml

我们经常用到的一个函数

simplexml_load_file(string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [,bool $is_prefix = false ]]]] )

 Interprets an XML file into an object.

Returns an object of class SimpleXMLElement with properties containing the data held within the XML document, or FALSE on failure.

一份典型的rss:

<?xml version="1.0" encoding="gb2312"?>
<rss version="2.0">
<channel>
<title>热点推荐</title>
<link>http://developer.51cto.com/col/1533</link>
<description>北京无忧创想信息技术有限公司 的 热点推荐 分类的最新内容</description>
<language>zh-cn</language>
<generator>power by 51CTO.COM</generator>
<webmaster>51cto@163.com</webmaster>
<item>
    <title>免费 jQuery UI 主题集合</title>
    <link>http://developer.51cto.com/art/201210/361211.htm</link>
    <description>本文整理了一些高度自定义、免费并且质量高的 jQuery UI 主题(如 Bootstrap 或 Windows-Metro),希望对你有所帮助。...</description>
   
</item>
<item>
    <title>完整的前端工程师面试问题列表</title>
    <link>http://developer.51cto.com/art/201210/361108.htm</link>
    <description>前言:@darcyclarke 在 GitHub 上分享了一个 repo,其中包括了不少前端面试问题,可用于检验潜在的候选人。绝不推荐在单个候选人身上用上所用的问题(那样会花费好几个小时滴)。从这个列表选择一些,应该能从候选人身上,检测出你所需要的技能。...</description>
   
</item>

</channel>
</rss>

Finding the feed title

The title for the entire feed (as distinct from the titles of the individual stories in the feed) resides in the title child of the channelchild of the rss root element. You can load this title as though the XML document were simply the serialized form of an object of class rss, with a channel field that itself had a title field. Using the regular PHP object reference syntax, this statement finds the title:

$title =  $rss->channel->title;

Having found the title, you must add it to the output HTML. Doing so is easy: Simply echo the $title variable:

<title><?php echo $title; ?></title>

Iterating through the items

Next, you must find the items in the feed. The expression that performs this task is obvious:

    $rss->channel->item

However, feeds generally contain more than one item. There might even be none of them. Consequently, this statement returns an array, which you can iterate across with a for-each loop:

foreach ($rss->channel->item as $item) {
  echo "<h2>" . $item->title . "</h2>";
  echo "<p>" . $item->description . "</p>";
} 

参考:http://www.ibm.com/developerworks/xml/library/x-simplexml/index.html

下面的例子是遍历google news:

<?php
$rss=simpleXML_load_file("http://news.google.com/news?ned=us&topic=h&output=rss");

echo '<h1>'.$rss->channel->title.'</h1>';

foreach($rss->channel->item as $item)
{
    echo '<h2><a href="'.$item->link.'">'.$item->title.'</a></h2>';
    echo '<p>'.$item->description.'</p>';
}

    
?>

另外一篇文章:

1 SimpleXML 简介 
要处理XML 文件,有两种传统的处理思路:SAX 和DOM。SAX 基于事件触发机制, 
对XML 文件进行一次扫描,完成要进行的处理;DOM 则将整个XML 文件构造为一棵DOM 
树,通过对DOM 树的遍历完成处理。这两种方法各有优缺点,SAX 的处理思路相对抽象, 
DOM 的处理过程相对烦琐,都不很适合新手的入门。 
PHP5 推出了一套新的XML 处理函数,即SimpleXML。名如其实,SimpleXML 本身小 
巧精干,只提供了少量的几个方法函数,但用它处理起XML 文件功能却非常强大,操作也 
非常的简单。 
首先,它提供有简单的函数可以从XML 文档、字符串、或DOM 对象上直接构造出 
SimpleXMLElement 对象;其次,SimpleXMLElement 提供有简单的方法可以进行属性、子节 
点、和XPath 的操作;然而,SimpleXML 最简单的地方是,它提供有使用标准对象的属性和 
对象迭代器进行节点操作的方法,这一处理思路使得用PHP 对XML 文档的处理得到了极大 
的简化。 
2 SimpleXML 入门示例 
下面我们通过一些小的代码片段,稍微了解一下SimpleXML 的强大和简洁。为举例方便, 
我们使用一个Messages.xml 文件,里面包含这样一段XML 代码: 
Messages.xml 

<?xml version='1.0' standalone='yes'?> 
<Messages> 
<msg id='1'> 
<title>This is Title</title> 
<content>Here is Content</content> 
<time>2008-03-20 21:50:23</time> 
<reply id='11'>reply 1</reply> 
<reply id='12'>reply 2</reply> 
</msg> 
</Messages> 

这是一篇保存有留言信息的XML 文档,每条信息包括属性id,子节点title、content、time 
以及若干条对于它的回复信息,每条回复包括属性id 及回复的内容。 
用SimpleXML 处理并输出此XML 文档内容的过程以及方法如下。 
(1) 构造SimpleXMLElement 对象 

代码片断 
$xml = simplexml_load_file('Messages.xml'); 
如果这段xml 已经被读入到一个字符串$messages 中,则可以使用如下语句: 
代码片断 
$xml = simplexml_load_string('Messages.xml'); 
(2)输出留言1 的标题 
代码片断 
//可以使用属性的方式访问子节点,通过节点的标签名可直接得到节点的内容 
echo $xml->msg->title; 
(3)输出留言1 的第一条回复信息 
代码片断 
//同级别的多个同名节点自动成为数组,可以通过索引下标访问其内容 
echo $xml->msg->reply[0]; 
(4)输出留言的id 
代码片断 
//节点的属性与值被封装成为关联数组的键与值 
echo $xml->msg['id']; 
(5)输出第二条回复的id 
代码片断 
//成为二维数组,第一维表示节点,第二维表示属性 
echo $xml->msg->reply[1][ 'id']; 
(6)依次输出所有回复的id 
代码片断 
//使用foreach 对同名节点进行遍历 
foreach ($xml->msg->reply as $reply){ 
echo $reply['id']; 

(7)使用XPath 检索所有的回复信息 
代码片断 
//xpath 方法直接检索定位(//表示任意深度) 
foreach ($xml->xpath('//reply') as $reply){ 
echo $reply.'<br>'; 


(8)遍历留言1 所有的子节点 
代码片断 
//children 方法得到所有子节点 
foreach ($xml->msg->children() as $field){ 
echo $field.'<br>'; 

(9)重新设置留言1 的发布时间 
代码片断 
//直接设置属性 
$xml->msg->time = '2008-03-21 00:53:12'; 
(10)设置回复2 的id 属性 
代码片断 
//设置管理数组的值 
$xml->msg->reply[1]['id'] = '222'; 
(11)新增一个描述消息作者的字段 
代码片断 
//直接设置属性 
$xml->msg->author = 'zhangsan'; 
(12)将消息的作者保存为属性 
代码片断 
//设置关联数组的key 
$xml->msg['author'] = 'zhangsan'; 
(13)重新保存对象到文件 
代码片断 
//保存 
$xml->asXML('MessagesNew.xml'); 
应该可以看出SimpleXML 有多简单了吧! 
3 实例:XML 文件与数据库之间进行数据交互 
下面提供一个相对完整的实例,将留言信息从MySQL 数据库中查询出来,保存成为一 
个如上例所示的XML 文件。留言信息和回复信息独立保存在两张表中,使用MySQL 函数包 
可以非常简单地实现如下: 

代码如下: 

<?php 
//cong work atWed Mar 20 19:59:04 CST 2008 
//将数据从MySQL 数据库中保存到XML 文件中 
//可以使用如下几种方式构造初始的SimpleXMLElement 对象 
//1、从DOM 对象中构造 
//$dom = new DOMDocument(); 
//$dom->loadXML("<rows></rows>"); 
//$xml = simplexml_import_dom($dom); 
//2、从仅包含根标签的xml 文件中构造 
//$xml = simplexml_load_file('messages.xml'); 
//3、直接写根标签字符串构造 
//$xml = simplexml_load_string("<Messages></Messages>"); 
//4、使用SimpleXMLElement 类的构造器构造 
$xml = new SimpleXMLElement('<Messages></Messages>'); 
//连接数据库 
mysql_connect('localhost','root','root'); 
mysql_select_db('test'); 
mysql_query('set names utf8'); 
//查询消息 
$rs = mysql_query("select * from messages"); 
$i = 0; //用做多条消息的数组索引下标 
while($row = mysql_fetch_assoc($rs)){ 
$xml->message[$i] = ''; //… … … … … … … … … … … … ① 
$xml->message[$i]['id'] = $row['id']; 
$xml->message[$i]->title = $row['title']; 
$xml->message[$i]->content = $row['content']; 
$xml->message[$i]->time = $row['time']; 
//根据消息id 查询它相关的回复信息 
$rsReply = mysql_query("select * from replies where mid={$row['id']}"); 
$j = 0; //用于做多条回复的索引下标 
while($rowReply = mysql_fetch_assoc($rsReply)){ 
$xml->message[$i]->reply[$j] = $rowReply['reply']; 
$xml->message[$i]->reply[$j]['id'] = $rowReply['id']; 
$j++; 
} 
$i++; 
} 
$xml->asXML('messages.xml'); 
?> 

上述代码唯一值得一提的地方就是标志①的那行。当我们要向一个SimpleXML 对象中新 
增一个节点或属性时,必须保证它的父节点是存在的,否则会报一个致命错误,提示信息是: 
Objects used as arrays in post/pre increment/decrement must return values by reference。

 

 

原文地址:https://www.cnblogs.com/youxin/p/2731797.html