xml解析類

轉載鏈接:http://zyan.cc/post/253


今天在PHP4環境下重新寫一個接口程序,需要大量分析解析XML,PHP的xml_parse_into_struct()函數不能直接生成便于使用的數組,而SimpleXML擴展在PHP5中才支持,于是逛逛搜索引擎,在老外的網站上找到了一個不錯的PHP XML操作類。

一、用法舉例:
1、將XML文件解釋成便于使用的數組:

    <?php  include('xml.php');    //引用PHP XML操作類  $xml = file_get_contents('data.xml');    //讀取XML文件  //$xml = file_get_contents("php://input");    //讀取POST過來的輸入流  $data=XML_unserialize($xml);  echo '<pre>';  print_r($data);  echo '</pre>';  ?>  

data.xml文件:
    <?xml version="1.0" encoding="GBK"?>  <video>  <upload>  <videoid>998</videoid>  <name><![CDATA[回憶未來]]></name>  <memo><![CDATA[def]]></memo>  <up_userid>11317</up_userid>  </upload>  </video>  

利用該XML操作類生成的對應數組(漢字編碼:UTF-8):
    Array  (  [video] => Array  (  [upload] => Array  (  [videoid] => 998  [name] => 回憶未來  [memo] => def  [up_userid] => 11317  )  )  )  

2、將數組轉換成XML文件:
    <?php  include('xml.php');//引用PHP XML操作類  $xml = XML_serialize($data);  ?>  


二、PHP XML操作類源代碼:
<?php   
###################################################################################   
#   
# XML Library, by Keith Devens, version 1.2b   
# <a href="http://keithdevens.com/software/phpxml" target="_blank">http://keithdevens.com/software/phpxml</a>   
#   
# This code is Open Source, released under terms similar to the Artistic License.   
# Read the license at <a href="http://keithdevens.com/software/license" target="_blank">http://keithdevens.com/software/license</a>   
#   
###################################################################################   ###################################################################################   
# XML_unserialize: takes raw XML as a parameter (a string)   
# and returns an equivalent PHP data structure   
###################################################################################   
function & XML_unserialize(&$xml){   $xml_parser = &new XML();   $data = &$xml_parser->parse($xml);   $xml_parser->destruct();   return $data;   
}   
###################################################################################   
# XML_serialize: serializes any PHP data structure into XML   
# Takes one parameter: the data to serialize. Must be an array.   
###################################################################################   
function & XML_serialize(&$data, $level = 0, $prior_key = NULL){   if($level == 0){ ob_start(); echo '<?xml version="1.0" ?>',"\n"; }   while(list($key, $value) = each($data))   if(!strpos($key, ' attr')) #if it's not an attribute  #we don't treat attributes by themselves, so for an emptyempty element   # that has attributes you still need to set the element to NULL   if(is_array($value) and array_key_exists(0, $value)){   XML_serialize($value, $level, $key);   }else{   $tag = $prior_key ? $prior_key : $key;   echo str_repeat("\t", $level),'<',$tag;   if(array_key_exists("$key attr", $data)){ #if there's an attribute for this element  while(list($attr_name, $attr_value) = each($data["$key attr"]))  echo ' ',$attr_name,'="',htmlspecialchars($attr_value),'"';  reset($data["$key attr"]);  }  if(is_null($value)) echo " />\n";  elseif(!is_array($value)) echo '>',htmlspecialchars($value),"</$tag>\n";  else echo ">\n",XML_serialize($value, $level+1),str_repeat("\t", $level),"</$tag>\n";  }  reset($data);  if($level == 0){ $str = &ob_get_contents(); ob_end_clean(); return $str; }  
}  
###################################################################################  
# XML class: utility class to be used with PHP's XML handling functions   
###################################################################################   
class XML{   var $parser;   #a reference to the XML parser   var $document; #the entire XML structure built up so far   var $parent;   #a pointer to the current parent - the parent will be an array   var $stack;    #a stack of the most recent parent at each nesting level   var $last_opened_tag; #keeps track of the last tag opened.   function XML(){   $this->parser = &xml_parser_create();   xml_parser_set_option(&$this->parser, XML_OPTION_CASE_FOLDING, false);   xml_set_object(&$this->parser, &$this);   xml_set_element_handler(&$this->parser, 'open','close');   xml_set_character_data_handler(&$this->parser, 'data');   }   function destruct(){ xml_parser_free(&$this->parser); }   function & parse(&$data){   $this->document = array();   $this->stack    = array();   $this->parent   = &$this->document;   return xml_parse(&$this->parser, &$data, true) ? $this->document : NULL;   }   function open(&$parser, $tag, $attributes){   $this->data = ''; #stores temporary cdata   $this->last_opened_tag = $tag;   if(is_array($this->parent) and array_key_exists($tag,$this->parent)){ #if you've seen this tag before  if(is_array($this->parent[$tag]) and array_key_exists(0,$this->parent[$tag])){ #if the keys are numeric  #this is the third or later instance of $tag we've come across   $key = count_numeric_items($this->parent[$tag]);   }else{   #this is the second instance of $tag that we've seen. shift around  if(array_key_exists("$tag attr",$this->parent)){  $arr = array('0 attr'=>&$this->parent["$tag attr"], &$this->parent[$tag]);  unset($this->parent["$tag attr"]);  }else{  $arr = array(&$this->parent[$tag]);  }  $this->parent[$tag] = &$arr;  $key = 1;  }  $this->parent = &$this->parent[$tag];  }else{  $key = $tag;  }  if($attributes) $this->parent["$key attr"] = $attributes;  $this->parent  = &$this->parent[$key];  $this->stack[] = &$this->parent;  }  function data(&$parser, $data){  if($this->last_opened_tag != NULL) #you don't need to store whitespace in between tags   $this->data .= $data;   }   function close(&$parser, $tag){   if($this->last_opened_tag == $tag){   $this->parent = $this->data;   $this->last_opened_tag = NULL;   }   array_pop($this->stack);   if($this->stack) $this->parent = &$this->stack[count($this->stack)-1];   }   
}   
function count_numeric_items(&$array){   return is_array($array) ? count(array_filter(array_keys($array), 'is_numeric')) : 0;   
}   
?>


本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/276164.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/276164.shtml
英文地址,請注明出處:http://en.pswp.cn/news/276164.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

jmeter學習指南之聚合報告

jmeter視頻地址&#xff1a;https://edu.51cto.com/course/14305.html 上一篇文章中我們講了Jmeter結果分析最常用的一個Listener查看結果樹&#xff0c;今天接著講另一個最常用的listener--聚合報告Aggregate Report。我們先來看看聚合報告中的主要名稱的含意&#xff1a;Labe…

敏捷開發概述

敏捷方法強調適應性而非預見性。 目前列入敏捷方法的有&#xff1a; 軟件開發節奏&#xff0c;Software Development Rhythms 敏捷數據庫技術&#xff0c;AD/Agile Database Techniques 敏捷建模&#xff0c;AM/Agile Modeling 自適應軟件開發&#xff0c;ASD/Adaptive Softwar…

2021 整理的最全學習資源,送給每一個努力著的人

時間來到了 2021 年&#xff0c;新的一年有新的期待&#xff0c;而我亦有新的祝福如果說在過去的一年&#xff0c;經歷太多&#xff0c;心酸、迷茫、焦慮、幸福、喜悅那么在 2021 年&#xff0c;希望你可以去過一種遇見自己的生活&#xff0c;恬淡、熱情&#xff0c;喜歡自己而…

ubuntu+php環境下的Memcached 安裝方法

轉載鏈接&#xff1a;http://www.jb51.net/article/28887.htm Memcached是一套分散式的高速緩存系統&#xff0c;當初是Danga Interactive為了LiveJournal所發展。 目前被很多系統所使用&#xff0c;例如Flick、Twitter等。這是一套開放源代碼軟件&#xff0c;以BSD license授…

php移動簽批源碼_PHP讓網站移動訪問更加友好方法

PHP都是在服務器上處理的&#xff0c;所以當代碼到達用戶時&#xff0c;它只是HTML。基本上&#xff0c;用戶從你的服務器請求你網站的一個頁面&#xff0c;然后你的服務器運行所有的PHP并向用戶發送PHP的結果。設備實際上從未看到或必須使用實際的PHP代碼。這使得使用PHP完成的…

Chrome OS 設備或將允許用戶自行選擇 Linux 發行版

百度智能云 云生態狂歡季 熱門云產品1折起>>> 谷歌去年宣布在 Chrome OS 上支持運行 Linux 應用&#xff0c;前不久又有消息稱其將為運行這些 Linux 應用提供 GPU 加速支持&#xff0c;而現在&#xff0c;Chrome OS 似乎將在 Linux 的方向上更進一步&#xff0c;讓 …

博文視點 OpenParty第11期:世界黑客大會那些事

博文視點 OpenParty第11期&#xff1a;世界黑客大會那些事 親愛的讀者朋友&#xff1a; 您好&#xff01; 2009年&#xff0c;博文視點Open Party共舉辦8場&#xff0c;累計到場2000人次&#xff0c;影響力輻射近5000人次&#xff0c;真正實現了博文視點Open Party的初…

我從 Vuejs 中學到了什么——框架設計學問

框架設計遠沒有大家想的那么簡單&#xff0c;并不是說只把功能開發完成&#xff0c;能用就算完事兒了&#xff0c;這里面還是有很多學問的。比如說&#xff0c;我們的框架應該給用戶提供哪些構建產物&#xff1f;產物的模塊格式如何&#xff1f;當用戶沒有以預期的方式使用框架…

CSS制作的32種圖形效果[梯形|三角|橢圓|平行四邊形|菱形|四分之一圓|旗幟]

轉載鏈接&#xff1a;http://www.w3cplus.com/css/css-simple-shapes-cheat-sheet 前面在《純CSS制作的圖形效果》一文中介紹了十六種CSS畫各種不同圖形的方法。今天花了點時間將這方面的制作成一份清單&#xff0c;方便大家急用時有地方可查。別的不多說了&#xff0c;直接看代…

vue-cli新建的項目webpack設置涉及的大部分插件整理

portfinder 用來檢測未占用的端口更多看這里: https://www.npmjs.com/package/portfinder webpack-merge 用來合并多個webpack設置&#xff0c;也可以合并對象更多看這里: https://www.npmjs.com/package/friendly-errors-webpack-plugin html-webpack-plugin 將html復制并插入…

yaml加配置文件后起不來_YAML配置文件管理資源

YAML是配置文件的格式&#xff0c;YAML文件中是由一些易讀的字段和指令組成的。K8S使用YAML配置文件需要注意如下事項。定義配置時&#xff0c;指定最新穩定版API(當前最新穩定版是v1版本)。最新版本的API可以通過kubectl api-versions命令進行查看&#xff0c;命令如下所示。前…

html5/css3響應式布局介紹

轉載鏈接&#xff1a;http://www.51xuediannao.com/htmlcss/htmlcssjq/694.html html5/css3響應式布局介紹 html5/css3響應式布局介紹及設計流程&#xff0c;利用css3的media query媒體查詢功能。移動終端一般都是對css3支持比較好的高級瀏覽器不需要考慮響應式布局的媒體查詢…

人際關系十大要訣

【一表人才】 所謂“一表人才”&#xff0c;就是說當你與陌生人第一次見面時給對方留下的第一印象&#xff0c;我們都知道第一印象很重要&#xff0c;要給對方留下好的印象&#xff0c;特別是要讓對方在最短的時間記住你。那么我們自身的儀表、行為舉止都很重要&#xff1b;我們…

MobX 上手指南,寫 Vue 的感覺?

之前用 Redux 比較多&#xff0c;一直聽說 Mobx 能讓你體驗到在 React 里面寫 Vue 的感覺&#xff0c;今天打算嘗試下 Mobx 是不是真的有寫 Vue 的感覺。題外話在介紹 MobX 的用法之前&#xff0c;先說點題外話&#xff0c;我們可以看一下 MobX 的中文簡介。在 MobX 的中文網站…

ansible中yaml語法應用

4、yaml語法應用 ansible的playbook編寫是yaml語言編寫&#xff0c;掌握yaml語法是編寫playbook的必要條件&#xff0c;格式要求和Python相似&#xff0c;具體教程參考如下yaml語言教程 附上一個yaml文件轉js格式文件鏈接在線免費yaml內容轉json格式 4.1、 ansible中的yaml語法…

中興a2018拆機圖片_中興天機拆機步驟詳解【圖文】

中興天機上市時有兩款&#xff0c;黑色和白色。黑色的缺點是外觀過于傳統&#xff0c;并不是很適合年輕人使用&#xff0c;但是其推出白色款卻很好的解決了這個問題。中興天機的整體性質與性價比完美的拼過了 小米 3等同時上線的手機產品。中興天機價格在1799左右&#xff0c;小…

網絡視頻貼片廣告全面推行第三方監測

視頻網站優酷與國際調研機構尼爾森聯合對外宣布&#xff1a;針對優酷視頻貼片廣告全面推行第三方監測。這是視頻行業首次倡導廣告投放數據透明化的一大舉措。  近年來&#xff0c;網絡視頻已經成為廣告主營銷的一大選擇。隨著廣告主投放額度不斷加大&#xff0c;廣告主對視頻…

css3動畫事件—webkitAnimationEnd

轉載鏈接&#xff1a;http://www.jb51.net/css/72443.html 用css3的animation完成一個動畫&#xff0c;當只有這個動畫完成時才執行令一個事件&#xff0c;比如讓動畫保持在終止的狀態或其他一些事件。我們該怎么辦呢。 第一種方法&#xff1a; 用計時器&#xff0c;設定一個…

(送書和紅包)快人一步,掌握前端函數式編程

大家好&#xff0c;我是若川。上周末送出了3本新書和若干紅包&#xff0c;抽獎名單已公布。本周又爭取到了4本《前端函數式編程》書籍包郵送給大家&#xff0c;抽獎規則見文末&#xff0c;與以往不同的是除了關鍵詞、留言、在看抽獎外&#xff0c;還有最早關注獎&#xff0c;歡…

js split參數為無效字符_js使用split函數按照多個字符對字符串進行分割的方法

{"moduleinfo":{"card_count":[{"count_phone":1,"count":1}],"search_count":[{"count_phone":5,"count":5}]},"card":[{"des":"阿里云函數計算(Function Compute)是一個事件…