This article mainly introduces php's mutual conversion between xml and json, and analyzes the principles and implementation skills of php's xml-to-json conversion and json-to-xml conversion based on examples, it has some reference value. This document describes how php converts xml to json. We will share this with you for your reference. The details are as follows:
Use php to convert xml and json:
For related functions, see The php Manual.
1. See xml below
Zhang San
Male
26
Tank
Yes
No
26
II. Convert xml into json
Use simplexml
Public function xml_to_json ($ source) {if (is_file ($ source) {// judge whether the file 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 later versions. for earlier versions, see JSON. phpreturn $ json ;}
3. convert json to xml
Recursive functions
Public function json_to_xml ($ source, $ charset = 'utf8') {if (empty ($ source) {return false;} // php5, and above. if it is an earlier version, view JSON. php $ array = json_decode ($ source); $ xml = ''; $ xml. = $ this-> change ($ array); return $ xml;} public function change ($ source) {$ string = ""; foreach ($ source as $ k =>$ v) {$ string. = "<". $ k. ">"; // determines whether it is an array, or if (is_array ($ v) | is_object ($ v )) {// is an array or a recursive call to the image $ string. = $ this-> change ($ v);} else {// Get tag data $ string. = $ v;} $ string. = "";} return $ string ;}
The preceding method json_to_xml can support Aaaa , Not supported Aaaaa You can understand the code.
For more articles about examples of php implementation of mutual conversion between xml and json, refer to PHP Chinese network!