参考 :PHP手册 (XML 元素结构例程)
- <?PHP
- header("content-type:text/html;charset=utf-8");
- //接口URL、
- $file='http://flash.weather.com.cn/wmaps/xml/china.xml';
- $result = array();//定义全局变量
- function startTag($parser,$name,$attrs)
- {
- global $result;
- $array=array();
- foreach ($attrs as $k=> $v){
- $array[strtolower($k)]=$v;
- }
- $result[][strtolower($name)]=$array;
- }
- function cdata($parser,$cdata)
- {
- global $result;
- if(trim($cdata))
- {
- $result[count($result)-1]['cdata']=$cdata;
- }
- }
- function endTag($parser,$name)
- {
- }
- //创建xml解析器
- $xml_parser = xml_parser_create();
- //定义XML的处理函数(处理器)
- xml_set_element_handler($xml_parser,"startTag","endTag");
- //打开文件资源
- if (!($fp = fopen($file,"r"))) {
- die("could not open XML input");
- }
- //循环处理数据
- while ($data = fread($fp,4096)) {
- if (!xml_parse($xml_parser,$data,feof($fp))) {
- die(sprintf("XML error: %s at line %d",xml_error_string(xml_get_error_code($xml_parser)),xml_get_current_line_number($xml_parser)));
- }
- }
- //释放解析器
- xml_parser_free($xml_parser);
- print("<pre>\n");
- var_dump($result);
- ?>