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!