Loaf
Loaf

Reputation: 3270

Converting Command cURL to php cUrl

I trying to convert the cURL code found here in the first example code. Here is the cURL they give me:

curl -X GET -H "Content-type: application/json" -d '{"api_key":"zUYwqLqwTqpyJ2bA7osy"}' https://statushub.io/api/status_pages

Here is what I have so far, and it isn't working:

<?php
#$cmd= 'curl -X GET -H "Content-type: application/json" -d \'{"api_key":"a991d51f4f7ea269ccfbfa68621b3aa3"}\' https://statushub.io/api/status_pages';
#exec($cmd,$result);
#echo gettype($result), "\n";
#echo print_r(curl_exec($cmd));

$ch = curl_init('https://statushub.io/api/status_pages');

curl_setopt($ch, CURLOPT_HTTPHEADER, 'Content-type: application/json');
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"api_key":"a991d51f4f7ea269ccfbfa68621b3aa3"}');
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$test = curl_exec($ch);
curl_close($ch);

echo (string)$test;

if(curl_exec($ch) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

echo "<pre>";
print_r($test);
echo "</pre>";
?>

I included some other attempts with lines coded out. I have tried looking at the php cURL documentation, but I can't figured this one out.

Thanks in advance.

Upvotes: 0

Views: 903

Answers (1)

John C
John C

Reputation: 8415

The following is a direct translation of the curl command, the only major difference I notice is that the headers are in an array and setting the CURLOPT_CUSTOMREQUEST to GET:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://statushub.io/api/status_pages");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"api_key":"zUYwqLqwTqpyJ2bA7osy"}');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$test = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

echo "<pre>";
print_r($test);
echo "</pre>";

Upvotes: 1

Related Questions