Home > Backend Development > PHP Problem > How to receive JSON data for POST using PHP

How to receive JSON data for POST using PHP

藏色散人
Release: 2023-03-12 08:14:02
Original
10680 people have browsed it

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);
Copy after login

First example:

<?php
$json = &#39;["PHP", "HTML", "javascript"]&#39;;

$data = json_decode($json);

echo $data[0];
Copy after login

Output result:

PHP
Copy after login

Second example:

<?php
$json = &#39;{
    "title": "PHP",
    "site": "PHP中文网"
}&#39;;

$data = json_decode($json);

echo $data->title;
echo "<br>";

echo $data->site;
Copy after login

Output:

PHP
PHP中文网
Copy after login

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!

Related labels:
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