Home >Backend Development >PHP Tutorial >How to Send JSON POST Requests with PHP?

How to Send JSON POST Requests with PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 07:48:03304browse

How to Send JSON POST Requests with PHP?

Sending JSON POST Requests with PHP

In this scenario, we aim to send JSON data to a specified URL via a POST request using PHP.

Problem Description

You possess JSON data and desire to post it to a JSON URL. The format of the JSON data is as follows:

{ 
    userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
    itemKind: 0,
    value: 1,
    description: 'Saude',
    itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}

The target URL for the POST request is:

http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount

Solution

To perform this task using PHP, you can utilize CURL. Here's an example code that demonstrates how to do it:

$url = "your url";    
$content = json_encode("your data to be sent");

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}


curl_close($curl);

$response = json_decode($json_response, true);

By utilizing this code, you can efficiently send your JSON data via a POST request to the specified URL.

The above is the detailed content of How to Send JSON POST Requests with PHP?. 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