Home >Backend Development >PHP Tutorial >How to Send JSON Data with Curl and PHP using PUT, POST, and GET?
When using curl in PHP to interact with a REST API, JSON data can be transmitted through three common HTTP request methods: PUT, POST, and GET. This article provides a detailed guide on how to achieve these data transfers effectively.
To perform a PUT request with a JSON payload, follow these steps:
$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);
For a POST request with JSON data, use this code:
$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);
As outlined in @Dan H's response, you can incorporate JSON data into a GET request by appending it to the URL as a query string:
$url .= '?data=' . urlencode(json_encode($data)); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch);
The above is the detailed content of How to Send JSON Data with Curl and PHP using PUT, POST, and GET?. For more information, please follow other related articles on the PHP Chinese website!