Home  >  Article  >  Backend Development  >  How to receive JSON in PHP and convert to array

How to receive JSON in PHP and convert to array

PHPz
PHPzOriginal
2023-04-18 10:25:48671browse

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.

  1. Receive JSON data

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:

  • file_get_contents is a PHP built-in function used to read file contents;
  • Here, we use PHP's input stream php://input to read the data submitted by POST in the form of a string;
  • Finally assign the read string to a variable.
  1. Parsing JSON data

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.

  1. Full example

Here is a complete implementation example:

// 从输入流中读取json数据
$json = file_get_contents('php://input');

// 解析json为数组
$data = json_decode($json, true);

// 打印数组内容
print_r($data);
  1. Summary

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!

Statement:
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