本文實例講述了PHP簡單實現解析xml為數組的方法。分享給大家供大家參考,具體如下:
最近想要做一個插件機制,需要用到xml,在解析xml時候需要轉換為數組,特意記錄一個此種解析方式
xmlDemo.xml文件:
?xml version="1.0" encoding="UTF-8"?>
main xmlns="http://www.xiaoetongo.cn" versionCode="1.0">
controller co="Aritles">
meth title="測試插件" do="aritle"/>
/controller>
controller co="Ari">
meth title="測試插件" do="ar"/>
meth title="測試插件" do="a"/>
/controller>
install>![CDATA[]]>/install>
upgrade>![CDATA[]]>/upgrade>
/main>
php代碼:
?php
$xmls=file_get_contents("xmlDemo.xml");
$xml =simplexml_load_string($xmls);
$xmljson= json_encode($xml);
$xml=json_decode($xmljson,true);
var_dump($xml);
運行結果:
array(4) {
["@attributes"]=>
array(1) {
["versionCode"]=>
string(3) "1.0"
}
["controller"]=>
array(2) {
[0]=>
array(2) {
["@attributes"]=>
array(1) {
["co"]=>
string(7) "Aritles"
}
["meth"]=>
array(1) {
["@attributes"]=>
array(2) {
["title"]=>
string(12) "測試插件"
["do"]=>
string(6) "aritle"
}
}
}
[1]=>
array(2) {
["@attributes"]=>
array(1) {
["co"]=>
string(3) "Ari"
}
["meth"]=>
array(2) {
[0]=>
array(1) {
["@attributes"]=>
array(2) {
["title"]=>
string(12) "測試插件"
["do"]=>
string(2) "ar"
}
}
[1]=>
array(1) {
["@attributes"]=>
array(2) {
["title"]=>
string(12) "測試插件"
["do"]=>
string(1) "a"
}
}
}
}
}
["install"]=>
array(0) {
}
["upgrade"]=>
array(0) {
}
}
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數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《php面向對象程序設計入門教程》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:- PHP實現的數組和XML文件相互轉換功能示例
- PHP實現使用DOM將XML數據存入數組的方法示例
- php實現XML和數組的相互轉化功能示例
- php實現xml轉換數組的方法示例
- PHP數組生成XML格式數據的封裝類實例
- PHP中數組轉換為SimpleXML教程