PHP cURL PUT Request with JSON Data Example

Sure, here’s an example of making a cURL PUT request using PHP:

<?php
// API endpoint URL
$apiUrl = 'https://example.com/api/endpoint';

// Data to be sent in the PUT request (as JSON in this example)
$data = array(
    'key1' => 'value1',
    'key2' => 'value2',
);

// Encode the data as JSON
$jsonData = json_encode($data);

// Create cURL resource
$ch = curl_init($apiUrl);

// Set cURL options for a PUT request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($jsonData)
));

// Execute the cURL request
$response = curl_exec($ch);

// Check for cURL errors
if (curl_errno($ch)) {
    echo 'cURL error: ' . curl_error($ch);
}

// Close cURL resource
curl_close($ch);

// Process the response
if ($response) {
    // Do something with the API response
    echo $response;
} else {
    // Handle the case where the request failed
    echo 'Request failed';
}
?>

Replace 'https://example.com/api/endpoint' with the actual API endpoint URL you want to call. Modify the $data array to include the data you want to send in the PUT request. The example encodes the data as JSON and sets the appropriate Content-Type header. Make sure to adjust the headers and data format based on the requirements of the API you are working with.