PHP中的XML解析的5种方法

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

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

【XML文件内容】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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解析】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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档案的节点,可以想像成游标走过整份文件的节点,并抓取需要的内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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对象创建整个文档的结构,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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 不同,使用例如 === 的运算符时要注意。

1
2
3
4
5
6
7
8
9
10
11
12
<?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的官方文档中有相关的例子,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 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;
?>

迎春舞会之三人组舞

【问题描述】
背景 Background
  HNSDFZ的同学们为了庆祝春节,准备排练一场舞

【描述 Description】
  n个人选出3*m人,排成m组,每组3人。
  站的队形——较矮的2个人站两侧,最高的站中间。
  从对称学角度来欣赏,左右两个人的身高越接近,则这一组的“残疾程度”越低。
  计算公式为 h=(a-b)^2 (a、b为较矮的2人的身高)
  那么问题来了。
  现在候选人有n个人,要从他们当中选出3*m个人排舞蹈,要求总体的“残疾程度”最低。

【输入格式 Input Format】
  第一排为m,n。
  第二排n个数字,保证升序排列。

【输出格式 Output Format】
  输出最小“残疾程度”。

【样例输入 Sample Input】
9 40
1 8 10 16 19 22 27 33 36 40 47 52 56 61 63 71 72 75 81 81 84 88 96 98 103 110 113 118 124 128 129 134 134 139 148 157 157 160 162 164

【样例输出 Sample Output】
23

注释 Hint
m<=1000,n<=5000 数据保证3*m<=n 【算法分析】 从大到小排序 a[i] f[i,j] 表示前i个数中有j对跳舞组合时的最优解 应为要最优就必须是排序时相邻两数的在两边才最好 而中间的人最高,记 f[i,j]=f[i-2,j-1]+(a[i]-a[i-1])^2 如果不取a[j]就 记 f[i,j]=f[i-1,j] 所以 f[i,j]=min{f[i,j]=f[i-2,j-1]+(a[i]-a[i-1])^2 | f[i,j]=f[i-1,j]} huyichen 摘自一大牛语录: 首先将筷子长度从短到长排序。 F[i,j,0]表示i个人使用前j双筷子,且第j根筷子不用,所需要长度差的平方和的最小值。 F[i,j,1]表示i个人使用前j双筷子,且使用第j根筷子,所需要长度差的平方和的最小值。 则F[i,j,0]=min{f[i,j-1,1],f[i,j-1,0]},F[i,j,1]=F[i-1,j-1,0]+(l[j]-l[j-1])^2 ans=min{F[k,n,1],F[k,n,0]} 算法复杂度为O(NK)。 算法正确性的简单证明: 因为筷子配对的时候要求是长度平方差最小,所以每根筷子的配对的时候总是希望和长度差最小的配对,即排序后相邻两根筷子是可以配对的。l[a],l,l[c],l[d]表示4根排序好的筷子。因为(l-l[a])^2+(l[d]-l[c])^2<(l-l[c])^2+(l[d]-l[a])^2,所以上述配对方法是正确的。 本题同样可以把模型直接转变为二分图最小权匹配。 将两根筷子相连的边权值标记为两根筷子长度平方差,然后对二分图求一次最小权匹配。可以使用网络流的最小费用K流的算法,寻找K次最短路的增广轨。 算法复杂度为O(KN^3)。 非常显然,动态规划的复杂度远远低于二分图最小权匹配的复杂度。 【代码】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <string.h>
 
int a[1001][5001];
int b[5001];
 
int main()
{
       int n, m, i, j, k, temp;
 
       scanf("%d%d", &m, &n);
       memset(b, 0, sizeof(b));
 
       for (i = 1; i <= n; i++)
              scanf("%d", &b[i]);
 
       for (i = 0; i <= m; i++)
       {
              for (j = 0; j <= n; j++)
                     a[i][j] = 2000000000;
       }
 
       for (i = 0; i <= n; i++)
              a[0][i] = 0;
 
       for (i = 1; i <= m; i++)
       {
              for (j = i + i; j <= n - (m - i) * 3; j++)
              {
                     a[i][j] = a[i][j - 1];
                     temp = a[i - 1][j - 2] + (b[j] - b[j - 1]) * (b[j] - b[j - 1]);
                     if ( j < n - (m - i) * 3 && temp < a[i][j])
                            a[i][j] = temp;
              }
       }
 
       printf("%d\n", a[m][n]);
       return 0;
}

JSON格式总结

【JSON是什么】
JSON,JavaScript Object Notation,一种更轻、更友好的用于接口(AJAX、REST等)数据交换的格式。JSON是结构化数据串行化的文本格式,作为XML的一种替代品,用于表示客户端与服务器间数据交换有效负载的格式。它是从ECMAScript语言标准衍生而来的。JSON的设计目标是使它成为小的、轻便的、文本的,而且是JavaScript的一个子集。
JSON能够描述四种简单的类型(字符串、数字、布尔值和null)和两种结构化类型(对象和数组)。

字符串(string)是零个或多个Unicode字符的序列。除了字符 “、\、/和一些控制符(\b,\f,\n,\r,\t)需要编码外,其他 Unicode 字符可以直接输出

对象(Object)是无次序的零个或多个名/值(name/value)对的集合,使用{}包含包含所有元素。这里的name是string类型,value则可以是string、number、boolean、null、Object或Array类型。

数组(Array)是零个或多个value的有序序列。JSON 还可以表示一个数组对象,使用 [] 包含所有元素,每个元素用逗号分隔,元素可以是任意的 Value。

Object 对象在 JSON 中是用 {} 包含一系列无序的 Key-Value 键值对表示的,key是string类型,value则可以是string、number、boolean、null、Object或Array类型。

“Object”和”Array”这两个术语来自JavaScript规范。

【JSON的优点】

  1. 数据格式比较简单, 易于读写, 格式都是压缩的, 占用带宽小
  2. 易于解析, 客户端JavaScript可以简单的通过eval()进行JSON数据的读取
  3. 支持多种语言, 包括ActionScript, C, C#, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby等语言服务器端语言, 便于服务器端的解析

【JSON的缺点】

  1. 没有XML格式这么推广的深入人心和使用广泛, 没有XML那么通用性
  2. JSON格式目前在Web Service中推广还属于初级阶段

【在PHP中使用JSON】
PHP中的json直接相关的函数只有json_encode和json_decode。其中json_encode只能接受 UTF-8 编码的字符串类型数据,所以此处我们可能用到iconv等编码转换函数。

在PHP5.2.0之后,可以使用json_encode直接操作服务器端的对象、数组等,能够直接生JSON格式, 便于客户端的访问提取。
另外,由于PHP中的数组是以HASH链表存在,可以使用非数字的关键字作为下标,所以,如果我们需要生成的数据是数组而不是对象时,需要数据的下标满足如下要求:

  • 必须是数字索引,
  • 必须从0开始,
  • 必须从小到依次增加,
  • 中间不可以弹跳下,
  • 位置不可变动.

这是由于在JS中数组是0开始的顺序序列,其余都只能是哈希表对象。如果要使用数组,可以使用array_values()函数。

【小结】
JSON 已经是 JavaScript. 标准的一部分。目前,主流的浏览器对 JSON 支持都非常完善。应用 JSON,我们可以从 XML 的解析中摆脱出来,对那些应用 Ajax 的 Web 2.0 网站来说,JSON 确实是目前最灵活的轻量级方案。

【参考资料】

http://ssgemail.javaeye.com/blog/36776

http://blog.csdn.net/kinglino520/archive/2009/03/30/4036449.aspx

http://hi.baidu.com/zhaofei299/blog/item/79ba4bf3473012c30b46e0d3.html