PHP简单实现解析xml为数组的方法

这篇文章主要介绍了PHP简单实现解析xml为数组的方法,涉及php文件读取、xml解析相关操作技巧,需要的朋友可以参考下。

本文实例讲述了PHP简单实现解析xml为数组的方法,分享给大家供大家参考,具体如下:

最近想要做一个插件机制,需要用到xml,在解析xml时候需要转换为数组,特意记录一个此种解析方式

xmlDemo.xml文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <main xmlns="http://www.xiaoetongo.cn" versionCode="1.0">
  3. <controller co="Aritles">
  4. <meth title="测试插件" do="aritle"/>
  5. </controller>
  6. <controller co="Ari">
  7. <meth title="测试插件" do="ar"/>
  8. <meth title="测试插件" do="a"/>
  9. </controller>
  10. <install><![CDATA[]]></install>
  11. <upgrade><![CDATA[]]></upgrade>
  12. </main>

php代码:

  1. <?php
  2. $xmls=file_get_contents("xmlDemo.xml");
  3. $xml =simplexml_load_string($xmls);
  4. $xmljson= json_encode($xml);
  5. $xml=json_decode($xmljson,true);
  6. var_dump($xml);

运行结果:

  1. array(4) {
  2. ["@attributes"]=>
  3. array(1) {
  4. ["versionCode"]=>
  5. string(3) "1.0"
  6. }
  7. ["controller"]=>
  8. array(2) {
  9. [0]=>
  10. array(2) {
  11. ["@attributes"]=>
  12. array(1) {
  13. ["co"]=>
  14. string(7) "Aritles"
  15. }
  16. ["meth"]=>
  17. array(1) {
  18. ["@attributes"]=>
  19. array(2) {
  20. ["title"]=>
  21. string(12) "测试插件"
  22. ["do"]=>
  23. string(6) "aritle"
  24. }
  25. }
  26. }
  27. [1]=>
  28. array(2) {
  29. ["@attributes"]=>
  30. array(1) {
  31. ["co"]=>
  32. string(3) "Ari"
  33. }
  34. ["meth"]=>
  35. array(2) {
  36. [0]=>
  37. array(1) {
  38. ["@attributes"]=>
  39. array(2) {
  40. ["title"]=>
  41. string(12) "测试插件"
  42. ["do"]=>
  43. string(2) "ar"
  44. }
  45. }
  46. [1]=>
  47. array(1) {
  48. ["@attributes"]=>
  49. array(2) {
  50. ["title"]=>
  51. string(12) "测试插件"
  52. ["do"]=>
  53. string(1) "a"
  54. }
  55. }
  56. }
  57. }
  58. }
  59. ["install"]=>
  60. array(0) {
  61. }
  62. ["upgrade"]=>
  63. array(0) {
  64. }
  65. }