What are the different methods for sending POST data using CURL in PHP?

When sending POST data using CURL in PHP, there are several methods to do so. One common method is to use the CURLOPT_POSTFIELDS option to set the data as an array. Another method is to use the CURLOPT_POSTFIELDS option to set the data as a URL-encoded string. Additionally, you can also use the CURLOPT_POSTFIELDS option to set the data as a JSON string.

// Method 1: Sending POST data as an array
$data = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);

// Method 2: Sending POST data as a URL-encoded string
$data = http_build_query(array(
    'key1' => 'value1',
    'key2' => 'value2'
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);

// Method 3: Sending POST data as a JSON string
$data = json_encode(array(
    'key1' => 'value1',
    'key2' => 'value2'
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
curl_close($ch);