实用版  |  综合版   推荐信息:CSS系列 | 网站排名 | 网页特效平面设计 | 硬件故障维修
内容

用PHP5的SimpleXML解析XML文档

出处:互联网   2008-03-13   浏览:    编辑:53vi.com
字体大小: | |
以下为引用的内容:
messages.xml
========================================================
<?xml version="1.0" ?>
<!--Sample XML document -->
<SystemMessage>
     <MessageTitle>System Down for Maintenance</MessageTitle>
    <MessageBody>Going down for maintenance soon!</MessageBody>
    <MessageAuthor>
   <MessageAuthorName>Joe SystemGod</MessageAuthorName>
   <MessageAuthorEmail>systemgod@someserver.com
</MessageAuthorEmail>
    </MessageAuthor>
    <MessageDate>March 4, 2004</MessageDate>
   <MessageNumber>10</MessageNumber>
</SystemMessage>
========================================================

xml 是一种创建元数据的语言,元数据是描述其它数据的数据,PHP中的XML处理是基于LIBXML2的,安装时默认开启。

 

 

可以通过phpinfo()函数查看是否开启了XML处理模块,DOM,LIBXML,SAMPLEXML。

首先,通过samplexml_load_file函数把xml文件加载到一个对象中,samplexml_load_file可以用户远程文件。

例如: [

$xml = samplexml_load_file("messages.xml"); // 本地文件系统,当前目录

 

 

$xml = samplexml_load_file("http://www.xml.org.cn/messages.xml"); // 远程web服务器

用 var_dump($xml) 和 print_r($xml) 分别输出其结构.var_dump给出了变量的类型和长度,而print_r可读性更强输出对象中的所有元素名称和它的值。

echo $xml->MessageTitle; //输出消息的标题

echo $xml->MessageBody; // 输出消息体

 

 

echo $xml->MessageAuthor; //消息的作者

echo $xml->MessageDate;  // 消息产生的日期

echo $xml->MessageNumber;  // 消息代码

 

 

===================================================

 

 

另外,还有一个函数,可以把XML字符串加载到一个simplexml对象中取。

 

 

 

以下为引用的内容:

$channel =<<<_XML_
<channel>
<title>What's For Dinner</title>
<link>http://menu.example.com/</link>
<description>These are your choices of what to eat tonight. </description>
</channel>
_XML_;

$xml = simplexml_load_string($channel);
===================================================

 

 

 

rss.xml

=============================================
<?xml version="1.0" encoding="utf-8"?>
<rss version="0.91">
<channel>
 <title>What's For Dinner</title>
 <link>http://menu.example.com/</link>
 <description>These are your choices of what to eat tonight.</description>
 <item>
  <title>Braised Sea Cucumber</title>
  <link>http://menu.example.com/dishes.php?dish=cuke</link>
  <description>Gentle flavors of the sea that nourish and refresh you. </description>
 </item>
 <item>
  <title>Baked Giblets with Salt</title>
  <link>http://menu.example.com/dishes.php?dish=giblets</link>
  <description>Rich giblet flavor infused with salt and spice. </description>
 </item>
 <item>
  <title>Abalone with Marrow and Duck Feet</title>

 

  <link>http://menu.example.com/dishes.php?dish=abalone</link>
  <description>There's no mistaking the special pleasure of abalone. </description>
 </item>
</channel>
</rss>
=====================================================

共3页: 上一页 1 [2] [3] 下一页
RSS               
发表评论请自觉遵守互联网相关政策法规
匿名
TMG

Copyright © 53vi.com, All Rights Reserved 资讯先锋网 版权所有

网站事务、投稿热线:815307530@qq.com