PHP實現(xiàn)的數(shù)組和XML文件相互轉換功能示例
本文實例講述了PHP實現(xiàn)的數(shù)組和XML文件相互轉換功能。分享給大家供大家參考,具體如下:
最近搞微信支付,微信服務器返回的都是XML文件,所以需要轉換成數(shù)組,才會便于操作,好了話不多說,直接上代碼:
1. XML轉數(shù)組
/**
* 將xml轉為array
* @param string $xml xml字符串或者xml文件名
* @param bool $isfile 傳入的是否是xml文件名
* @return array 轉換得到的數(shù)組
*/
function xmlToArray($xml,$isfile=false){
//禁止引用外部xml實體
libxml_disable_entity_loader(true);
if($isfile){
if(!file_exists($xml)) return false;
$xmlstr = file_get_contents($xml);
}else{
$xmlstr = $xml;
}
$result= json_decode(json_encode(simplexml_load_string($xmlstr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $result;
}
用法示例:
$xmlDoc=<<<ETO <books> <book> <author>Jack Herrington</author> <title>PHP Hacks</title> <publisher>O'Reilly</publisher> </book> <book> <author>Jack Herrington</author> <title>Podcasting Hacks</title> <publisher>O'Reilly</publisher> </book> <book> <author>XML格式化</author> <title>腳本之家在線工具</title> <publisher>tools.jb51.net</publisher> </book> </books> ETO; $relarr=xmlToArray($xmlDoc); print_r($relarr);
運行結果:
Array
(
[book] => Array
(
[0] => Array
(
[author] => Jack Herrington
[title] => PHP Hacks
[publisher] => O'Reilly
)
[1] => Array
(
[author] => Jack Herrington
[title] => Podcasting Hacks
[publisher] => O'Reilly
)
[2] => Array
(
[author] => XML格式化
[title] => 腳本之家在線工具
[publisher] => tools.jb51.net
)
)
)
2. 數(shù)組轉XML
/**
* 數(shù)組轉xml字符
* @param string $xml xml字符串
**/
function arrayToXml($data){
if(!is_array($data) || count($data) <= 0){
return false;
}
$xml = "<xml>";
foreach ($data as $key=>$val){
if (is_numeric($val)){
$xml.="<".$key.">".$val."</".$key.">";
}else{
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
}
$xml.="</xml>";
return $xml;
}
用法示例:
$arrDoc= array("author"=>"XML格式化","title"=>"腳本之家在線工具","publisher"=>"tools.jb51.net");
$xmlrel=arrayToXml($arrDoc);
//運行結果:<xml><author><![CDATA[XML格式化]]></author><title><![CDATA[腳本之家在線工具]]></title><publisher><![CDATA[tools.jb51.net]]></publisher></xml>
PS:這里再為大家提供幾款關于xml操作的在線工具供大家參考使用:
在線XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP針對XML文件操作技巧總結》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結》、《PHP錯誤與異常處理方法總結》、《PHP基本語法入門教程》、《php面向對象程序設計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
php空間不支持socket但支持curl時recaptcha的用法
php空間不支持socket但支持curl時recaptcha的用法,需要的朋友可以參考下。2011-11-11

