Home >Backend Development >PHP Problem >How to receive JSON in PHP and convert to array
In PHP, it is usually necessary to receive JSON data sent by other applications or front-ends and convert it into an array for subsequent processing. This article will introduce how to receive JSON and convert it into an array in PHP.
In PHP, you can receive JSON data passed by the front end through the $_POST or $_GET global variable. The following example transmits and receives JSON data through POST:
$json = file_get_contents('php://input');
Detailed explanation:
Next, we need to convert the read JSON string into an array in PHP. PHP provides the built-in function json_decode Used to convert JSON data into PHP arrays. Specific examples are as follows:
$data = json_decode($json, true);
In the above code, we pass the read JSON data to the json_decode function. The second parameter is set to true, which means that an associative array will be returned, otherwise an object will be returned.
Note: If the JSON format is incorrect, the parsing process may fail, and json_decode will return null. Therefore, be sure to ensure that the JSON data format is correct before parsing.
Here is a complete implementation example:
// 从输入流中读取json数据 $json = file_get_contents('php://input'); // 解析json为数组 $data = json_decode($json, true); // 打印数组内容 print_r($data);
In PHP Receiving and parsing JSON data becomes very simple. This is done by reading a JSON string from the input stream and converting it into an array using the built-in json_decode function. At the same time, you must ensure the correctness of the data format before receiving data to avoid parsing errors.
The above is the detailed content of How to receive JSON in PHP and convert to array. For more information, please follow other related articles on the PHP Chinese website!