Example of mutual conversion between xml and json in php, xmljson
The example in this article 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
<? Xml version = "1.0" encoding = "UTF-8"?> <Humans> <zhangying> <name> Zhang San </name> <sex> male </sex> <old> 26 </old> </zhangying> <tank> <name> tank </name> <sex>
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 json_to_xml method supports <name> aaaa </name> and does not support <name type = 'test'> aaaaa </name>.
PS: This site also provides the following XML and JSON-related tools for your reference:
Online XML/JSON conversion tools:
Http://tools.jb51.net/code/xmljson
Php code online formatting and beautification tools:
Http://tools.jb51.net/code/phpformat
Online XML formatting/compression tools:
Http://tools.jb51.net/code/xmlformat
Json code online formatting/beautification/compression/editing/conversion tools:
Http://tools.jb51.net/code/jsoncodeformat
C language style/HTML/CSS/json code formatting and beautification tools:
Http://tools.jb51.net/code/ccode_html_css_json