Home >Backend Development >PHP Tutorial >How to Send JSON POST Requests Using PHP and CURL?

How to Send JSON POST Requests Using PHP and CURL?

Susan Sarandon
Susan SarandonOriginal
2024-11-16 09:18:03915browse

How to Send JSON POST Requests Using PHP and CURL?

Send JSON POST Request with PHP

In this scenario, you have JSON data that you need to POST to a specified JSON URL. To accomplish this task in PHP, you can utilize the CURL library. Here's an example of how you can implement 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);

In this code, you initialize the CURL request by specifying the URL and necessary options. The JSON data is encoded and set as the POST parameters. After executing the request, you check the HTTP status code to ensure success and handle any errors. Finally, the JSON response is decoded and stored in the $response variable for further processing.

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