PHP Simple Implementation of Parsing xml into Arrays

  • 2021-10-11 17:49:49
  • OfStack

In this paper, an example is given to describe the simple implementation of PHP to parse xml into arrays. Share it for your reference, as follows:

Want to do a plug-in mechanism recently, need to use xml, when parsing xml need to convert into an array, specially record one such parsing mode

xmlDemo. xml file:


<?xml version="1.0" encoding="UTF-8"?>
<main xmlns="http://www.xiaoetongo.cn" versionCode="1.0">
<controller co="Aritles">
<meth title=" Test plug-in " do="aritle"/>
</controller>
<controller co="Ari">
<meth title=" Test plug-in " do="ar"/>
<meth title=" Test plug-in " do="a"/>
</controller>
<install><![CDATA[]]></install>
<upgrade><![CDATA[]]></upgrade>
</main>

php code:


<?php
$xmls=file_get_contents("xmlDemo.xml");
$xml =simplexml_load_string($xmls);
$xmljson= json_encode($xml);
$xml=json_decode($xmljson,true);
var_dump($xml);

Run results:


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) " Test plug-in "
     ["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) " Test plug-in "
      ["do"]=>
      string(2) "ar"
     }
    }
    [1]=>
    array(1) {
     ["@attributes"]=>
     array(2) {
      ["title"]=>
      string(12) " Test plug-in "
      ["do"]=>
      string(1) "a"
     }
    }
   }
  }
 }
 ["install"]=>
 array(0) {
 }
 ["upgrade"]=>
 array(0) {
 }
}

PS: Here are several online tools for xml operation for your reference:

Online XML/JSON Interconversion Tool:
http://tools.ofstack.com/code/xmljson

Online Formatting XML/Online Compressing XML:
http://tools.ofstack.com/code/xmlformat

XML Online Compression/Formatting Tools:
http://tools.ofstack.com/code/xml_format_compress

XML code online formatting beautification tool:
http://tools.ofstack.com/code/xmlcodeformat

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of PHP Operation Skills for XML File", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Introduction to php Object-Oriented Programming", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: