Home > Backend Development > PHP Tutorial > How to Parse JSON POST Request Bodies in PHP without PECL?

How to Parse JSON POST Request Bodies in PHP without PECL?

Patricia Arquette
Release: 2024-12-08 21:53:12
Original
655 people have browsed it

How to Parse JSON POST Request Bodies in PHP without PECL?

Parsing JSON POST Request Bodies in PHP without PECL

Retrieving and parsing JSON request bodies in PHP scripts can be challenging, particularly when dealing with POST requests. This article addresses the issue of accessing and interacting with POST-ed JSON objects in PHP, without the use of HTTP request body function calls like http_get_request_body().

Solution

To effectively parse JSON POST request bodies in PHP without PECL, a simple and straightforward approach is to utilize the following two steps:

  1. Read the request body into a string using $inputJSON = file_get_contents('php://input');.
  2. Convert the JSON string into an array using $input = json_decode($inputJSON, TRUE);.

The second parameter in json_decode (TRUE) ensures that the JSON object is returned as an array, facilitating easy access to its properties and values.

Sample Code

Here's a sample PHP script that demonstrates the above approach:

<?php

// Read the JSON request body
$inputJSON = file_get_contents('php://input');

// Convert the JSON string to an array
$input = json_decode($inputJSON, TRUE);

// Access and interact with the JSON object
// (e.g., print the value of a property)
echo $input['name'];

?>
Copy after login

The above is the detailed content of How to Parse JSON POST Request Bodies in PHP without PECL?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template