分类目录归档:PHP

PHP源码,PHP扩展,PHP程序

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;
?>

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

PHP遍历文件的4种方法

【常规遍历方法】
常规遍历方法是指从PHP4开始就可以使用的方法,它是结合使用opendir()函数和readdir()函数,通过打开目录,读取目录和关闭目录,逐一判断列出所有的文件。简单实现代码如下:

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
/**
 * 获取当前目录及子目录下的所有文件
 * @param string $dir 路径名
 * @return array 所有文件的路径数组
 */
function get_files1($dir) {
    $files = array();
 
    if(!is_dir($dir)) {
        return $files;
    }
 
    $handle = opendir($dir);
    if($handle) {
        while(false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $filename = $dir . "/"  . $file;
                if(is_file($filename)) {
                    $files[] = $filename;
                }else {
                    $files = array_merge($files, get_files($filename));
                }
            }
        }   //  end while
        closedir($handle);
    }
    return $files;
}   //  end function

【使用glob】
glob() 函数依照 libc glob() 函数使用的规则寻找所有与 pattern 匹配的文件路径,类似于一般 shells 所用的规则一样。不进行缩写扩展或参数替代。
返回一个包含有匹配文件/目录的数组。如果出错返回 FALSE。
此函数不能作用于远程文件,被检查的文件必须通过服务器的文件系统访问。

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
<?PHP
/**
 * 获取当前目录下的所有文件
 * @param string $dir 路径名
 * @return array 所有文件的路径数组
 */
function get_files($dir) {
    $dir = realpath($dir) . "/";
    $files  = array();
 
    if (!is_dir($dir)) {
        return $files;
    }
 
    $pattern =  $dir . "*";
    $file_arr = glob($pattern);
 
    foreach ($file_arr as $file) {
        if (is_dir($file)) {
            $temp = get_files($file);
 
            if (is_array($temp)) {
                $files = array_merge($files, $temp);
            }
        }else {
            $files[] = $file;
        }   //  end if
    }
    return $files;
}   //  end function
?>

【使用directory 类】
这是个仿冒面向对象的机制来读取一个目录。
dir() 函数打开一个目录句柄,并返回一个对象。这个对象包含三个方法:read() , rewind() 以及 close()。并且有两个属性可用。handle 属性可以用在其它目录函数例如 readdir(),rewinddir() 和 closedir() 中。path 属性被设为被打开的目录路径。
若成功,则该函数返回一个目录流,否则返回 false 以及一个 error。可以通过在函数名前加上 “@” 来隐藏 error 的输出。

注意: read 方法返回的目录项的顺序依赖于系统。
注意: 本函数定义了内部类 Directory,意味着不能再用同样的名字定义用户自己的类。

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
/**
 * 递归显示当前指定目录下所有文件
 * 使用dir函数
 * @param string $dir 目录地址
 * @return array $files 文件列表
 */
function get_files($dir) {
    $files = array();
 
    if (!is_dir($dir)) {
        return $files;
    }
 
    $d = dir($dir);
    while (false !== ($file = $d->read())) {
        if ($file != '.' && $file != '..') {
            $filename = $dir . "/"  . $file;
 
            if(is_file($filename)) {
                $files[] = $filename;
            }else {
                $files = array_merge($files, get_files($filename));
            }
        }
    }
    $d->close();
    return $files;
}

【RecursiveDirectoryIterator类】
此方法自PHP 5.0有效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
 * 使用RecursiveDirectoryIterator遍历文件,列出所有文件路径
 * @param RecursiveDirectoryIterator $dir 指定了目录的RecursiveDirectoryIterator实例
 * @return array $files 文件列表
 */
function get_files($dir) {
    $files = array();
 
    for (; $dir->valid(); $dir->next()) {
        if ($dir->isDir() && !$dir->isDot()) {
            if ($dir->haschildren()) {
                $files = array_merge($files, get_files($dir->getChildren()));
            };
        }else if($dir->isFile()){
            $files[] = $dir->getPathName();
        }
    }
    return $files;
}
 
$path = "/var/www";
$dir = new RecursiveDirectoryIterator($path);
print_r(get_files($dir));

需要了解此类的其它信息请移步 http://www.php.net/~helly/php/ext/spl/