Today, I want to find a method to convert xml into json on the internet. I haven't found it for a long time. I found it, and it's useless. One of the service_JSON statements is really true, search for the JSON file. php and php5.0 have already been added, json_decode and json_encode. I want to take shortcuts. The following is a method I wrote:
1. Refer to the xml file as follows:
The code is as follows: |
Copy code |
<? Xml version = "1.0" encoding = "UTF-8"?> <Humans> <Zhangying> <Name> Zhang Ying </name> <Sex> male </sex> <Old> 28 </old> </Zhangying> <Tank> <Name> tank </name> <Sex> <Hao> yes <Aaaa> no </aaaa> </Sex> <Old> 28 </old> </Tank> </Humans> |
2. Convert xml to json
Use simplexml
The code is as follows: |
Copy code |
Public function xml_to_json ($ source ){ If (is_file ($ source) {// Determine whether the object is passed or the xml string $ Xml_array = simplexml_load_file ($ source ); } Else { $ Xml_array = simplexml_load_string ($ source ); } $ Json = json_encode ($ xml_array); // php5, and above. If it is an earlier version ,? Lower? JSON. php Return $ json; } 3. json |
Convert to xml
Recursive functions
The code is as follows: |
Copy code |
Public function json_to_xml ($ source, $ charset = 'utf8 '){ If (emptyempty ($ source )){ Return false; } $ Array = json_decode ($ source); // php5, and above. If it is an earlier version ,? Lower? JSON. php $ Xml = '<! -- L version = "1.0" encoding = "'. $ charset.' --> '; $ Xml. = $ this-> change ($ array ); Return $ xml; } Public function change ($ source ){ $ String = ""; Foreach ($ source as $ k => $ v ){ $ String. = "<". $ k. "> "; If (is_array ($ v) | is_object ($ v) {// determines whether it is an array or $ String. = $ this-> change ($ v); // It is an array or a recursive call to the image. } Else { $ String. = $ v; // Obtain tag data } $ String. = ""; } Return $ string; } |
The preceding json_to_xml method supports <name> aaaa </name> and does not support <name type = 'test'> aaaaa </name>.