Home >Backend Development >PHP Tutorial >How to Use Curl and PHP to Send JSON Data for REST API CRUD Operations?

How to Use Curl and PHP to Send JSON Data for REST API CRUD Operations?

DDD
DDDOriginal
2024-11-23 02:28:10946browse

How to Use Curl and PHP to Send JSON Data for REST API CRUD Operations?

How to Pass JSON Data with Curl and PHP for PUT, POST, GET, and DELETE

Utilizing Curl and PHP for CRUD operations on REST APIs is a convenient approach. While the command line offers straightforward methods to pass JSON data, PHP requires a customized implementation.

PHP Curl Implementation for PUT:

<?php
$data = array('username' => 'dog', 'password' => 'tall');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>

PHP Curl Implementation for POST:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>

PHP Curl Implementation for GET (Alternative Approach):

<?php
$query_string = http_build_query($data);
$url = $url . '?' . $query_string;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>

PHP Curl Implementation for DELETE:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>

The above is the detailed content of How to Use Curl and PHP to Send JSON Data for REST API CRUD Operations?. 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