Home > Backend Development > PHP Tutorial > How to Send JSON Data via POST Request using PHP cURL?

How to Send JSON Data via POST Request using PHP cURL?

Patricia Arquette
Release: 2024-11-17 14:16:02
Original
907 people have browsed it

How to Send JSON Data via POST Request using PHP cURL?

POSTing JSON Data with PHP

This inquiry seeks guidance on sending JSON data via a POST request in PHP. The following code snippet demonstrates how to achieve this using CURL:

<?php

$url = "http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount";
$data = json_encode([
    'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
    'itemKind' => 0,
    'value' => 1,
    'description' => 'Saude',
    'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
]);

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

$response = curl_exec($ch);

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

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

curl_close($ch);

$response = json_decode($response, true);

?>
Copy after login

In this example, $url represents the target URL, and $data contains the JSON data that will be posted. The curl_init() function initiates the CURL session, and subsequent curl_setopt() calls set the necessary options. The curl_exec() function sends the request and returns the server's response, which is then processed and decoded as needed.

The above is the detailed content of How to Send JSON Data via POST Request using PHP cURL?. 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