This article is an example of the PHP implementation of XML and JSON conversion between the function. Share to everyone for your reference, specific as follows:
Implement the conversion of XML to JSON using PHP:
For related functions, check the PHP manual.
First, reference XML is as follows
<?xml version= "1.0" encoding= "UTF-8"?>
Translating XML into JSON
Using SimpleXML
The Public Function Xml_to_json ($source) {
if (Is_file ($source)) {//Is the judge of the file, 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 the earlier version, please check json.php return
$json;
}
Third, JSON converted to XML
Using Recursive functions
Public Function Json_to_xml ($source, $charset = ' utf8 ') {
if (empty ($source)) {return
false;
}
PHP5, and above, if the earlier version, please check the json.php
$array = Json_decode ($source);
$xml = ';
$xml. = $this->change ($array);
return $xml;
}
The Public Function change ($source) {
$string = "";
foreach ($source as $k => $v) {
$string. = "<". $k. " > ";
To determine whether it is an array, or, for an image
if (Is_array ($v) | | is_object ($v)) {
//is an array or recursive call to an image
$string. = $this->change ($v);
else{
//Get Tag data
$string. = $v;
}
$string. = "";
}
return $string;
}
The above method is Json_to_xml, can support <NAME>AAAA</NAME>, and does not support <name type= ' test ' >aaaaa</name> look at the code to understand.
PS: This site also provides the following XML and JSON-related tools to facilitate reference for everyone to use:
Online Xml/json Mutual Conversion tool:
Http://tools.jb51.net/code/xmljson
PHP code online format Landscaping tools:
Http://tools.jb51.net/code/phpformat
Online XML format/compression tools:
Http://tools.jb51.net/code/xmlformat
JSON code online Format/beautify/compress/edit/Convert tools:
Http://tools.jb51.net/code/jsoncodeformat
C Language Style/html/css/json code formatting landscaping Tools:
Http://tools.jb51.net/code/ccode_html_css_json
For more information about PHP interested readers can view the site topics: "PHP JSON format data Operation tips Summary", "PHP for XML file Operation skills Summary", "PHP basic Grammar Introductory Course", "PHP Array" Operation Techniques Encyclopedia, "PHP string ( String) Usage summary, "Getting Started with Php+mysql database operations" and "Summary of common PHP database Operations Tips"
I hope this article will help you with the PHP program design.