Introducing JSON and XML format conversion in PHP

PHPz
Release: 2023-03-31 09:48:28
Original
753 people have browsed it

During the development process, data format conversion is a common problem. In PHP, the two commonly used data formats are JSON and XML. JSON is a lightweight data exchange format that is easy to read and write, while XML is an extensible markup language that is widely used in Web data transmission and configuration file storage.

This article will introduce how to convert JSON format to XML format in PHP.

1. JSON to XML

PHP provides the function json_decode() that can be used to convert JSON data into XML format. The syntax is as follows:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
Copy after login

Among them, $json represents the JSON string to be converted, $assoc represents whether to convert the JSON object into an associative array (default is false), $depth represents the maximum recursion depth (default is 512 ), $options represents conversion options (default is 0).

The following is an example of converting a JSON array into XML:

<?php
// JSON数据
$json_data = &#39;{
    "students": [
        {
            "name": "David",
            "age": 20,
            "score": {
                "English": 90,
                "Math": 85,
                "Chinese": 95
            }
        },
        {
            "name": "Tom",
            "age": 22,
            "score": {
                "English": 80,
                "Math": 75,
                "Chinese": 85
            }
        }
    ]
}&#39;;

// 将JSON数据转换成PHP数组
$php_data = json_decode($json_data, true);

// 将PHP数组转换成XML格式
$xml_data = new SimpleXMLElement(&#39;<?xml version="1.0" encoding="UTF-8"?><data></data>');
array_to_xml($php_data, $xml_data);

// 输出XML格式数据
header('Content-type: text/xml');
echo $xml_data->asXML();

// 将数组转换成XML格式的函数
function array_to_xml($arr, &$xml) {
    foreach ($arr as $key => $value) {
        if (is_array($value)) {
            if (!is_numeric($key)) {
                $subnode = $xml->addChild("$key");
                array_to_xml($value, $subnode);
            } else {
                array_to_xml($value, $xml);
            }
        } else {
            $xml->addChild("$key", htmlspecialchars("$value"));
        }
    }
}
?>
Copy after login

The above code first converts the JSON string into a PHP array, and then uses a recursive function to convert the PHP array into XML format.

The output XML format data is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <students>
    <0>
      <name>David</name>
      <age>20</age>
      <score>
        <English>90</English>
        <Math>85</Math>
        <Chinese>95</Chinese>
      </score>
    </0>
    <1>
      <name>Tom</name>
      <age>22</age>
      <score>
        <English>80</English>
        <Math>75</Math>
        <Chinese>85</Chinese>
      </score>
    </1>
  </students>
</data>
Copy after login

2. XML to JSON

To convert XML format to JSON format, you need to convert XML to PHP array first, and then Use the json_encode() function to convert a PHP array into a JSON string. The following is an example of converting XML to JSON:

children() as $element) {
        if (count($element->children()) == 0) {
            $arr[$element->getName()] = strval($element);
        } else {
            $arr[$element->getName()][] = xml_to_array($element);
        }
    }
    return $arr;
}
?>
Copy after login

The above code first converts the XML string into a SimpleXMLElement object through the simplexml_load_string() function, and then converts the SimpleXMLElement object into a PHP array through the recursive function. Finally, use the json_encode() function to convert the PHP array into a JSON string.

The output JSON format data is as follows:

{
  "students": [
    {
      "name": "David",
      "age": "20",
      "score": {
        "English": "90",
        "Math": "85",
        "Chinese": "95"
      }
    },
    {
      "name": "Tom",
      "age": "22",
      "score": {
        "English": "80",
        "Math": "75",
        "Chinese": "85"
      }
    }
  ]
}
Copy after login

Summary

PHP provides convenient functions for converting JSON format to XML format and XML format to JSON format. During the development process, choosing the appropriate data format for storage and exchange based on actual needs can achieve better data transmission and reading effects.

The above is the detailed content of Introducing JSON and XML format conversion in PHP. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template