【前言】
不管是桌面软件开发,还是WEB应用,XML无处不在!
然而在平时的工作中,仅仅是使用一些已经封装好的类对XML对于处理,包括生成,解析等。假期有空,于是将PHP中的几种XML解析方法总结如下:

以解析Google API 接口提供的天气情况为例,我们取今天的天气及气温。
API地址:http://www.google.com/ig/api?weather=shenzhen

【XML文件内容】

<?xml version="1.0"?>
<xml_api_reply version="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
<forecast_information>
<city data="Shenzhen, Guangdong"/>
<postal_code data="shenzhen"/>
<latitude_e6 data=""/>
<longitude_e6 data=""/>
<forecast_date data="2009-10-05"/>
<current_date_time data="2009-10-04 05:02:00 +0000"/>
<unit_system data="US"/>
</forecast_information>
<current_conditions>
<condition data="Sunny"/>
<temp_f data="88"/>
<temp_c data="31"/>
<humidity data="Humidity: 49%"/>
<icon data="/ig/images/weather/sunny.gif"/>
<wind_condition data="Wind: mph"/>
</current_conditions>
</weather>
</xml_api_reply>

【使用DomDocument解析】

<?PHP
header("Content-type:text/html; Charset=utf-8");
$url = "http://www.google.com/ig/api?weather=shenzhen"; // 加载XML内容
$content = file_get_contents($url);
$content = get_utf8_string($content);
$dom = DOMDocument::loadXML($content);
/*
此处也可使用如下所示的代码,
$dom = new DOMDocument();
$dom->load($url);
*/ $elements = $dom->getElementsByTagName("current_conditions");
$element = $elements->item(0);
$condition = get_google_xml_data($element, "condition");
$temp_c = get_google_xml_data($element, "temp_c");
echo '天气:', $condition, '<br />';
echo '温度:', $temp_c, '<br />'; function get_utf8_string($content) { // 将一些字符转化成utf8格式
$encoding = mb_detect_encoding($content, array('ASCII','UTF-8','GB2312','GBK','BIG5'));
return mb_convert_encoding($content, 'utf-8', $encoding);
} function get_google_xml_data($element, $tagname) {
$tags = $element->getElementsByTagName($tagname); // 取得所有的$tagname $tag = $tags->item(0); // 获取第一个以$tagname命名的标签
if ($tag->hasAttributes()) { // 获取data属性
$attribute = $tag->getAttribute("data");
return $attribute;
}else {
return false;
}
}
?>

这只是一个简单的示例,仅包括了loadXML, item, getAttribute,getElementsByTagName等方法,还有一些有用的方法,这个依据你的实际需要。

【XMLReader】
当我们要用php解读xml的内容时,有很多物件提供函式,让我们不用一个一个字元去解析,而只要根据标签和属性名称,就能取出文件中的属性与内容了,相较之下方便许多。其中XMLReader循序地浏览过xml档案的节点,可以想像成游标走过整份文件的节点,并抓取需要的内容。

<?PHP
header("Content-type:text/html; Charset=utf-8");
$url = "http://www.google.com/ig/api?weather=shenzhen"; // 加载XML内容
$xml = new XMLReader();
$xml->open($url); $condition = '';
$temp_c = '';
while ($xml->read()) {
// echo $xml->name, "==>", $xml->depth, "<br>";
if (!empty($condition) && !empty($temp_c)) {
break;
}
if ($xml->name == 'condition' && empty($condition)) { // 取第一个condition
$condition = $xml->getAttribute('data');
} if ($xml->name == 'temp_c' && empty($temp_c)) { // 取第一个temp_c
$temp_c = $xml->getAttribute('data');
} $xml->read();
} $xml->close();
echo '天气:', $condition, '<br />';
echo '温度:', $temp_c, '<br />';

我们只是需要取第一个condition和第一个temp_c,于是遍历所有的节点,将遇到的第一个condition和第一个temp_c写入变量,最后输出。

【DOMXPath】
这种方法需要使用DOMDocument对象创建整个文档的结构,

<?PHP
header("Content-type:text/html; Charset=utf-8");
$url = "http://www.google.com/ig/api?weather=shenzhen"; // 加载XML内容
$dom = new DOMDocument();
$dom->load($url); $xpath = new DOMXPath($dom);
$element = $xpath->query("/xml_api_reply/weather/current_conditions")->item(0);
$condition = get_google_xml_data($element, "condition");
$temp_c = get_google_xml_data($element, "temp_c");
echo '天气:', $condition, '<br />';
echo '温度:', $temp_c, '<br />'; function get_google_xml_data($element, $tagname) {
$tags = $element->getElementsByTagName($tagname); // 取得所有的$tagname $tag = $tags->item(0); // 获取第一个以$tagname命名的标签
if ($tag->hasAttributes()) { // 获取data属性
$attribute = $tag->getAttribute("data");
return $attribute;
}else {
return false;
}
}
?>

【xml_parse_into_struct】
说明:int xml_parse_into_struct ( resource parser, string data, array &values [, array &index] )

该函数将 XML 文件解析到两个对应的数组中,index 参数含有指向 values 数组中对应值的指针。最后两个数组参数可由指针传递给函数。
注意: xml_parse_into_struct() 失败返回 0,成功返回 1。这和 FALSE 与 TRUE 不同,使用例如 === 的运算符时要注意。

<?PHP
header("Content-type:text/html; Charset=utf-8");
$url = "http://www.google.com/ig/api?weather=shenzhen"; // 加载XML内容
$content = file_get_contents($url);
$p = xml_parser_create();
xml_parse_into_struct($p, $content, $vals, $index);
xml_parser_free($p); echo '天气:', $vals[$index['CONDITION'][0]]['attributes']['DATA'], '<br />';
echo '温度:', $vals[$index['TEMP_C'][0]]['attributes']['DATA'], '<br />';

【Simplexml】
此方法在PHP5中可用
这个在google的官方文档中有相关的例子,如下:

// Charset: utf-8
/**
* 用php Simplexml 调用google天气预报api,和g官方的例子不一样
* google 官方php domxml 获取google天气预报的例子
* http://www.google.com/tools/toolbar/buttons/intl/zh-CN/apis/howto_guide.html
*
* @copyright Copyright (c) 2008 <cmpan(at)qq.com>
* @license New BSD License
* @version 2008-11-9
*/ // 城市,用城市拼音
$city = empty($_GET['city']) ? 'shenzhen' : $_GET['city'];
$content = file_get_contents("http://www.google.com/ig/api?weather=$city&hl=zh-cn");
$content || die("No such city's data");
$content = mb_convert_encoding($content, 'UTF-8', 'GBK');
$xml = simplexml_load_string($content); $date = $xml->weather->forecast_information->forecast_date->attributes();
$html = $date. "<br>\r\n"; $current = $xml->weather->current_conditions; $condition = $current->condition->attributes();
$temp_c = $current->temp_c->attributes();
$humidity = $current->humidity->attributes();
$icon = $current->icon->attributes();
$wind = $current->wind_condition->attributes(); $condition && $condition = $xml->weather->forecast_conditions->condition->attributes();
$icon && $icon = $xml->weather->forecast_conditions->icon->attributes(); $html.= "当前: {$condition}, {$temp_c}°C,<img src='http://www.google.com/ig{$icon}'/> {$humidity} {$wind} <br />\r\n"; foreach($xml->weather->forecast_conditions as $forecast) {
$low = $forecast->low->attributes();
$high = $forecast->high->attributes();
$icon = $forecast->icon->attributes();
$condition = $forecast->condition->attributes();
$day_of_week = $forecast->day_of_week->attributes();
$html.= "{$day_of_week} : {$high} / {$low} °C, {$condition} <img src='http://www.google.com/ig{$icon}' /><br />\r\n";
} header('Content-type: text/html; Charset: utf-8');
print $html;
?>

PHP中的XML解析的5种方法的更多相关文章

  1. XML解析的二种方法之dom解析

    XML解析的二种方法:dom解析和sax解析 文件大小      存储位置          读取速度 dom解析     小文件      放在内存中              快 sax解析   ...

  2. python实现XML解析的三种方法

    python实现XML解析的三种方法 三种方法:一是xml.dom.*模块,它是W3C DOM API的实现,若需要处理DOM API则该模块很适合:二是xml.sax.*模块,它是SAX API的实 ...

  3. .net中创建xml文件的两种方法

    .net中创建xml文件的两种方法 方法1:根据xml结构一步一步构建xml文档,保存文件(动态方式) 方法2:直接加载xml结构,保存文件(固定方式) 方法1:动态创建xml文档 根据传递的值,构建 ...

  4. XML解析的四种方法 建议使用demo4j解析 测试可以用

    https://www.cnblogs.com/longqingyang/p/5577937.html 4.DOM4J解析  特征: 1.JDOM的一种智能分支,它合并了许多超出基本XML文档表示的功 ...

  5. XML 解析的两种方法

    申请博客有一段时间了,一直没有写些什么,今天写一下被遗忘的 xml,因为 ios 现在一般都用 JSON,但毕竟还有一部分老一些的服务器还会有 xml xml 格式的解析方式有两种 1.SAX解析: ...

  6. XML解析的二种方法之Sax解析

    package com.huawei.xml; import java.io.InputStream;import java.util.Stack; import javax.xml.parsers. ...

  7. 解决在php5中simple XML解析错误的问题

    2004年7月,php5正式版本的发布,标志着一个全新的PHP时代的到来.PHP5的最大特点是引入了面向对象的全部机制,并且保留了向下的兼容性.程序员不必再编写缺乏功能性的类,并且能够以多种方法实现类 ...

  8. PHP怎么读写XML?(四种方法)

    PHP怎么读写XML?(四种方法) 一.总结 1.这四种方法中,字符串的方式是最原始的方法.SimpleXML和DOM扩展是属于基于树的解析器,把整个文档存储为树的数据结构中,需要把整个文档都加载到内 ...

  9. 在Oracle中执行动态SQL的几种方法

    转载:在Oracle中执行动态SQL的几种方法 以下为内容留存: 在Oracle中执行动态SQL的几种方法 在一般的sql操作中,sql语句基本上都是固定的,如:SELECT t.empno,t.en ...

随机推荐

  1. ajax常用参数

    url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址.前台跳转到后台 请求参数:前台向后台传数据 回调函数:回调函数就是一个自定义的函数在发生特定的事件的时候调用来处理这个事件 ...

  2. php js表单登陆验证

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  3. linux下忘记mysql root密码解决办法

    vi /etc/my.cnf    #编辑文件,找到[mysqld],在下面添加一行skip-grant-tables [mysqld] skip-grant-tables :wq!  #保存退出 s ...

  4. geotools

    http://blog.tigerlihao.cn/2010/01/geotools-based-web-map-service.html

  5. 安装Elasticsearch,Logstash,Kibana(5.0.1-mac版)

    安装Elasticsearch 1.下载https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.0.1.tar.gz包 ...

  6. po line received is canceled(恢复PO被取消的余量)

    1張PO已部分收貨,後來由于某種原因,將部分收貨的PO明行取消,現在要對已收料的這一部分進行退貨處理,要怎麼做才好呢? [@more@]DATA COLLECTED===============COL ...

  7. ThinkPHP讲解(一)框架基础

    ThinkPHP框架知识点过于杂乱,接下来将以问题的形势讲解tp(ThinkPHP的简写) 1.tp框架是什么,为什么使用是它? 一堆代码的集合,里边有变量.函数.类.常量,里边也有许多设计模式MVC ...

  8. zw版【转发·台湾nvp系列Delphi例程】HALCON CheckDifference

    zw版[转发·台湾nvp系列Delphi例程]HALCON CheckDifference unit Unit1;interfaceuses Windows, Messages, SysUtils, ...

  9. IE和FF区别关于css和js

    css 1.ul标签FF中有padding值,没有margin,IE中相反 解决办法:将ul的padding和margin都设为0, js 1.IE中innerText在火狐中没有,使用textCon ...

  10. Swift 注释

    注释就是对代码的解释和说明.目的是为了让别人和自己很容易看懂.为了让别人一看就知道这段代码是做什么用的. 正确的程序注释一般包括序言性注释和功能性注释.序言性注释的主要内容包括模块的接口.数据的描述和 ...