免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2448 | 回复: 1
打印 上一主题 下一主题

PHP XML Library:一个不错的PHP XML操作类 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-11-08 17:28 |只看该作者 |倒序浏览
 PHP XML Library:一个不错的PHP XML操作类



今天在PHP4环境下重新写一个接口程序,需要大量分析解析XML,PHP的xml_parse_into_struct()函数不能直接生成便于使用的数组,而SimpleXML扩展在PHP5中才支持,于是逛逛搜索引擎,在老外的网站上找到了一个不错的PHP XML操作类。

一、用法举例:
1、将XML文件解释成便于使用的数组:

view plaincopy to clipboardprint?
  1. 1.<?php   
  2. 2.include('xml.php');    //引用PHP XML操作类   
  3. 3.$xml = file_get_contents('data.xml');    //读取XML文件   
  4. 4.//$xml = file_get_contents("php://input");    //读取POST过来的输入流   
  5. 5.$data=XML_unserialize($xml);   
  6. 6.echo '<pre>';   
  7. 7.print_r($data);   
  8. 8.echo '</pre>';   
  9. 9.?>  
复制代码
Php代码
  1. 1.<?php   
  2. 2.include('xml.php');    //引用PHP XML操作类   
  3. 3.$xml = file_get_contents('data.xml');    //读取XML文件   
  4. 4.//$xml = file_get_contents("php://input");    //读取POST过来的输入流   
  5. 5.$data=XML_unserialize($xml);   
  6. 6.echo '<pre>';   
  7. 7.print_r($data);   
  8. 8.echo '</pre>';   
  9. 9.?>  
  10. <?php
  11. include('xml.php');    //引用PHP XML操作类
  12. $xml = file_get_contents('data.xml');    //读取XML文件
  13. //$xml = file_get_contents("php://input");    //读取POST过来的输入流
  14. $data=XML_unserialize($xml);
  15. echo '<pre>';
  16. print_r($data);
  17. echo '</pre>';
  18. ?>
复制代码
data.xml文件:
  1. view plaincopy to clipboardprint?
  2. 1.<?xml version="1.0" encoding="GBK"?>  
  3. 2.<video>   
  4. 3.<upload>   
  5. 4.<videoid>998</videoid>   
  6. 5.<name><![CDATA[回忆未来]]></name>   
  7. 6.<memo><![CDATA[def]]></memo>   
  8. 7.<up_userid>11317</up_userid>   
  9. 8.</upload>   
  10. 9.</video>   
  11. Xml代码
  12. 1.<?xml version="1.0" encoding="GBK"?>  
  13. 2.<video>  
  14. 3.<upload>  
  15. 4.<videoid>998</videoid>  
  16. 5.<name><![CDATA[回忆未来]]></name>  
  17. 6.<memo><![CDATA[def]]></memo>  
  18. 7.<up_userid>11317</up_userid>  
  19. 8.</upload>  
  20. 9.</video>  
  21. <?xml version="1.0" encoding="GBK"?>
  22. <video>
  23. <upload>
  24. <videoid>998</videoid>
  25. <name><![CDATA[回忆未来]]></name>
  26. <memo><![CDATA[def]]></memo>
  27. <up_userid>11317</up_userid>
  28. </upload>
  29. </video>
复制代码
利用该XML操作类生成的对应数组(汉字编码:UTF-8):

  1. view plaincopy to clipboardprint?
  2. 1.Array   
  3. 2.(   
  4. 3.    [video] => Array   
  5. 4.        (   
  6. 5.            [upload] => Array   
  7. 6.                (   
  8. 7.                    [videoid] => 998   
  9. 8.                    [name] => 回忆未来   
  10. 9.                    [memo] => def   
  11. 10.                    [up_userid] => 11317   
  12. 11.                )   
  13. 12.  
  14. 13.        )   
  15. 14.  
  16. 15.)  
复制代码
Html代码
  1. 1.Array   
  2. 2.(   
  3. 3.    [video] => Array   
  4. 4.        (   
  5. 5.            [upload] => Array   
  6. 6.                (   
  7. 7.                    [videoid] => 998   
  8. 8.                    [name] => 回忆未来   
  9. 9.                    [memo] => def   
  10. 10.                    [up_userid] => 11317   
  11. 11.                )   
  12. 12.  
  13. 13.        )   
  14. 14.  
  15. 15.)  
  16. Array
  17. (
  18.     [video] => Array
  19.         (
  20.             [upload] => Array
  21.                 (
  22.                     [videoid] => 998
  23.                     [name] => 回忆未来
  24.                     [memo] => def
  25.                     [up_userid] => 11317
  26.                 )

  27.         )

  28. )
复制代码
2、将数组转换成XML文件:
  1. view plaincopy to clipboardprint?
  2. 1.<?php   
  3. 2.include('xml.php');//引用PHP XML操作类   
  4. 3.$xml = XML_serialize($data);   
  5. 4.?>  
复制代码
Php代码
  1. 1.<?php   
  2. 2.include('xml.php');//引用PHP XML操作类   
  3. 3.$xml = XML_serialize($data);   
  4. 4.?>  
  5. <?php
  6. include('xml.php');//引用PHP XML操作类
  7. $xml = XML_serialize($data);
  8. ?>
复制代码
二、PHP XML操作类源代码:

view plaincopy to clipboardprint?
  1. 1.<?php   
  2. 2.###################################################################################   
  3. 3.#   
  4. 4.# XML Library, by Keith Devens, version 1.2b   
  5. 5.# <a href="http://keithdevens.com/software/phpxml" target="_blank">http://keithdevens.com/software/phpxml</a>     
  6. 6.#   
  7. 7.# This code is Open Source, released under terms similar to the Artistic License.   
  8. 8.# Read the license at <a href="http://keithdevens.com/software/license" target="_blank">http://keithdevens.com/software/license</a>     
  9. 9.#   
  10. 10.###################################################################################   
  11. 11.  
  12. 12.###################################################################################   
  13. 13.# XML_unserialize: takes raw XML as a parameter (a string)     
  14. 14.# and returns an equivalent PHP data structure     
  15. 15.###################################################################################   
  16. 16.function & XML_unserialize(&$xml){     
  17. 17.    $xml_parser = &new XML();     
  18. 18.    $data = &$xml_parser->parse($xml);     
  19. 19.    $xml_parser->destruct();     
  20. 20.    return $data;     
  21. 21.}   
  22. 22.###################################################################################   
  23. 23.# XML_serialize: serializes any PHP data structure into XML   
  24. 24.# Takes one parameter: the data to serialize. Must be an array.     
  25. 25.###################################################################################   
  26. 26.function & XML_serialize(&$data, $level = 0, $prior_key = NULL){     
  27. 27.    if($level == 0){ ob_start(); echo '<?xml version="1.0" ?>',"\n"; }     
  28. 28.    while(list($key, $value) = each($data))     
  29. 29.        if(!strpos($key, ' attr')) #if it's not an attribute   
  30. 30.            #we don't treat attributes by themselves, so for an emptyempty element   
  31. 31.            # that has attributes you still need to set the element to NULL   
  32. 32.  
  33. 33.            if(is_array($value) and array_key_exists(0, $value)){     
  34. 34.                XML_serialize($value, $level, $key);     
  35. 35.            }else{     
  36. 36.                $tag = $prior_key ? $prior_key : $key;     
  37. 37.                echo str_repeat("\t", $level),'<',$tag;     
  38. 38.                if(array_key_exists("$key attr", $data)){ #if there's an attribute for this element   
  39. 39.                    while(list($attr_name, $attr_value) = each($data["$key attr"]))   
  40. 40.                        echo ' ',$attr_name,'="',htmlspecialchars($attr_value),'"';   
  41. 41.                    reset($data["$key attr"]);   
  42. 42.                }   
  43. 43.
  44. 44.                if(is_null($value)) echo " />\n";   
  45. 45.                elseif(!is_array($value)) echo '>',htmlspecialchars($value),"</$tag>\n";   
  46. 46.                else echo ">\n",XML_serialize($value, $level+1),str_repeat("\t", $level),"</$tag>\n";   
  47. 47.            }   
  48. 48.    reset($data);   
  49. 49.    if($level == 0){ $str = &ob_get_contents(); ob_end_clean(); return $str; }   
  50. 50.}   
  51. 51.###################################################################################   
  52. 52.# XML class: utility class to be used with PHP's XML handling functions   
  53. 53.###################################################################################   
  54. 54.class XML{     
  55. 55.    var $parser;   #a reference to the XML parser     
  56. 56.    var $document; #the entire XML structure built up so far     
  57. 57.    var $parent;   #a pointer to the current parent - the parent will be an array     
  58. 58.    var $stack;    #a stack of the most recent parent at each nesting level     
  59. 59.    var $last_opened_tag; #keeps track of the last tag opened.     
  60. 60.  
  61. 61.    function XML(){     
  62. 62.         $this->parser = &xml_parser_create();     
  63. 63.        xml_parser_set_option(&$this->parser, XML_OPTION_CASE_FOLDING, false);     
  64. 64.        xml_set_object(&$this->parser, &$this);     
  65. 65.        xml_set_element_handler(&$this->parser, 'open','close');     
  66. 66.        xml_set_character_data_handler(&$this->parser, 'data');     
  67. 67.    }   
  68. 68.    function destruct(){ xml_parser_free(&$this->parser); }     
  69. 69.    function & parse(&$data){     
  70. 70.        $this->document = array();     
  71. 71.        $this->stack    = array();     
  72. 72.        $this->parent   = &$this->document;     
  73. 73.        return xml_parse(&$this->parser, &$data, true) ? $this->document : NULL;     
  74. 74.    }   
  75. 75.    function open(&$parser, $tag, $attributes){     
  76. 76.        $this->data = ''; #stores temporary cdata     
  77. 77.        $this->last_opened_tag = $tag;     
  78. 78.        if(is_array($this->parent) and array_key_exists($tag,$this->parent)){ #if you've seen this tag before   
  79. 79.            if(is_array($this->parent[$tag]) and array_key_exists(0,$this->parent[$tag])){ #if the keys are numeric   
  80. 80.                #this is the third or later instance of $tag we've come across   
  81. 81.                $key = count_numeric_items($this->parent[$tag]);     
  82. 82.            }else{     
  83. 83.                #this is the second instance of $tag that we've seen. shift around   
  84. 84.                if(array_key_exists("$tag attr",$this->parent)){   
  85. 85.                    $arr = array('0 attr'=>&$this->parent["$tag attr"], &$this->parent[$tag]);   
  86. 86.                    unset($this->parent["$tag attr"]);   
  87. 87.                }else{   
  88. 88.                    $arr = array(&$this->parent[$tag]);   
  89. 89.                }   
  90. 90.                $this->parent[$tag] = &$arr;   
  91. 91.                $key = 1;   
  92. 92.            }   
  93. 93.            $this->parent = &$this->parent[$tag];   
  94. 94.        }else{   
  95. 95.            $key = $tag;   
  96. 96.        }   
  97. 97.        if($attributes) $this->parent["$key attr"] = $attributes;   
  98. 98.        $this->parent  = &$this->parent[$key];   
  99. 99.        $this->stack[] = &$this->parent;   
  100. 100.    }   
  101. 101.    function data(&$parser, $data){   
  102. 102.        if($this->last_opened_tag != NULL) #you don't need to store whitespace in between tags   
  103. 103.            $this->data .= $data;     
  104. 104.    }   
  105. 105.    function close(&$parser, $tag){     
  106. 106.        if($this->last_opened_tag == $tag){     
  107. 107.            $this->parent = $this->data;     
  108. 108.            $this->last_opened_tag = NULL;     
  109. 109.        }   
  110. 110.        array_pop($this->stack);     
  111. 111.        if($this->stack) $this->parent = &$this->stack[count($this->stack)-1];     
  112. 112.    }   
  113. 113.}   
  114. 114.function count_numeric_items(&$array){     
  115. 115.    return is_array($array) ? count(array_filter(array_keys($array), 'is_numeric')) : 0;     
  116. 116.}   
  117. 117.?>   
复制代码
Php代码
[code]1.<?php   
2.###################################################################################   
3.#   
4.# XML Library, by Keith Devens, version 1.2b   
5.# <a href="http://keithdevens.com/software/phpxml" target="_blank">http://keithdevens.com/software/phpxml</a>   
6.#   
7.# This code is Open Source, released under terms similar to the Artistic License.   
8.# Read the license at <a href="http://keithdevens.com/software/license" target="_blank">http://keithdevens.com/software/license</a>   
9.#   
10.###################################################################################   
11.  
12.###################################################################################   
13.# XML_unserialize: takes raw XML as a parameter (a string)   
14.# and returns an equivalent PHP data structure   
15.###################################################################################   
16.function & XML_unserialize(&$xml){   
17.    $xml_parser = &new XML();   
18.    $data = &$xml_parser->parse($xml);   
19.    $xml_parser->destruct();   
20.    return $data;   
21.}   
22.###################################################################################   
23.# XML_serialize: serializes any PHP data structure into XML   
24.# Takes one parameter: the data to serialize. Must be an array.   
25.###################################################################################   
26.function & XML_serialize(&$data, $level = 0, $prior_key = NULL){   
27.    if($level == 0){ ob_start(); echo '<?xml version="1.0" ?>',"\n"; }   
28.    while(list($key, $value) = each($data))   
29.        if(!strpos($key, ' attr')) #if it's not an attribute   
30.            #we don't treat attributes by themselves, so for an emptyempty element   
31.            # that has attributes you still need to set the element to NULL   
32.  
33.            if(is_array($value) and array_key_exists(0, $value)){   
34.                XML_serialize($value, $level, $key);   
35.            }else{   
36.                $tag = $prior_key ? $prior_key : $key;   
37.                echo str_repeat("\t", $level),'<',$tag;   
38.                if(array_key_exists("$key attr", $data)){ #if there's an attribute for this element   
39.                    while(list($attr_name, $attr_value) = each($data["$key attr"]))   
40.                        echo ' ',$attr_name,'="',htmlspecialchars($attr_value),'"';   
41.                    reset($data["$key attr"]);   
42.                }   
43.  
44.                if(is_null($value)) echo " />\n";   
45.                elseif(!is_array($value)) echo '>',htmlspecialchars($value),"</$tag>\n";   
46.                else echo ">\n",XML_serialize($value, $level+1),str_repeat("\t", $level),"</$tag>\n";   
47.            }   
48.    reset($data);   
49.    if($level == 0){ $str = &ob_get_contents(); ob_end_clean(); return $str; }   
50.}   
51.###################################################################################   
52.# XML class: utility class to be used with PHP's XML handling functions   
53.###################################################################################   
54.class XML{   
55.    var $parser;   #a reference to the XML parser   
56.    var $document; #the entire XML structure built up so far   
57.    var $parent;   #a pointer to the current parent - the parent will be an array   
58.    var $stack;    #a stack of the most recent parent at each nesting level   
59.    var $last_opened_tag; #keeps track of the last tag opened.   
60.  
61.    function XML(){   
62.         $this->parser = &xml_parser_create();   
63.        xml_parser_set_option(&$this->parser, XML_OPTION_CASE_FOLDING, false);   
64.        xml_set_object(&$this->parser, &$this);   
65.        xml_set_element_handler(&$this->parser, 'open','close');   
66.        xml_set_character_data_handler(&$this->parser, 'data');   
67.    }   
68.    function destruct(){ xml_parser_free(&$this->parser); }   
69.    function & parse(&$data){   
70.        $this->document = array();   
71.        $this->stack    = array();   
72.        $this->parent   = &$this->document;   
73.        return xml_parse(&$this->parser, &$data, true) ? $this->document : NULL;   
74.    }   
75.    function open(&$parser, $tag, $attributes){   
76.        $this->data = ''; #stores temporary cdata   
77.        $this->last_opened_tag = $tag;   
78.        if(is_array($this->parent) and array_key_exists($tag,$this->parent)){ #if you've seen this tag before   
79.            if(is_array($this->parent[$tag]) and array_key_exists(0,$this->parent[$tag])){ #if the keys are numeric   
80.                #this is the third or later instance of $tag we've come across   
81.                $key = count_numeric_items($this->parent[$tag]);   
82.            }else{   
83.                #this is the second instance of $tag that we've seen. shift around   
84.                if(array_key_exists("$tag attr",$this->parent)){   
85.                    $arr = array('0 attr'=>&$this->parent["$tag attr"], &$this->parent[$tag]);   
86.                    unset($this->parent["$tag attr"]);   
87.                }else{   
88.                    $arr = array(&$this->parent[$tag]);   
89.                }   
90.                $this->parent[$tag] = &$arr;   
91.                $key = 1;   
92.            }   
93.            $this->parent = &$this->parent[$tag];   
94.        }else{   
95.            $key = $tag;   
96.        }   
97.        if($attributes) $this->parent["$key attr"] = $attributes;   
98.        $this->parent  = &$this->parent[$key];   
99.        $this->stack[] = &$this->parent;   
100.    }   
101.    function data(&$parser, $data){   
102.        if($this->last_opened_tag != NULL) #you don't need to store whitespace in between tags   
103.            $this->data .= $data;   
104.    }   
105.    function close(&$parser, $tag){   
106.        if($this->last_opened_tag == $tag){   
107.            $this->parent = $this->data;   
108.            $this->last_opened_tag = NULL;   
109.        }   
110.        array_pop($this->stack);   
111.        if($this->stack) $this->parent = &$this->stack[count($this->stack)-1];   
112.    }   
113.}   
114.function count_numeric_items(&$array){   
115.    return is_array($array) ? count(array_filter(array_keys($array), 'is_numeric')) : 0;   
116.}   
117.?>   
<?php

http://blog.s135.com/post/253/ 转载

论坛徽章:
0
2 [报告]
发表于 2011-11-14 09:58 |只看该作者
谢谢楼主
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP