In the previous article "How PHP program traverses json data", we introduced how PHP traverses json data. Then this article will continue to introduce PHP json related content. I hope you will continue to read~
This article explains how PHP receives POST JSON data.
If you have read the previous article, you must have a certain understanding of json, so I won’t introduce it here.
First of all, let me introduce three important knowledge points to you:
1, php://input
: This is a read-only stream , allowing us to read raw data from the request body. It returns all raw data after the request's HTTP headers, regardless of content type.
2, file_get_contents()
Function: This function in PHP is used to read a file into a string.
3, json_decode()
Function: This function accepts a JSON string and converts it into a PHP variable, which can be an array or object.
I believe everyone knows that we can use the $_POST[] global variable to receive all published data in PHP scripts. But when we want to receive JSON string as post data, it fails. So if we want to receive a JSON string, we can use "php://input" and the file_get_contents() function to help us receive the JSON data as a file and read it into a string.
Let’s introduce it through specific examples:
Use the json_decode() function to decode the JSON string.
// 从请求中获取原始数据 $json = file_get_contents('php://input'); // 将其转换为 PHP 对象 $data = json_decode($json);
First example:
<?php $json = '["PHP", "HTML", "javascript"]'; $data = json_decode($json); echo $data[0];
Output result:
PHP
Second example:
<?php $json = '{ "title": "PHP", "site": "PHP中文网" }'; $data = json_decode($json); echo $data->title; echo "<br>"; echo $data->site;
Output:
PHP PHP中文网
PHP Chinese website platform has a lot of video teaching resources. Welcome everyone to learn "PHP Video Tutorial"!
The above is the detailed content of How to receive JSON data for POST using PHP. For more information, please follow other related articles on the PHP Chinese website!