将命令cURL转换为php cUrl

时间:2016-02-18 03:10:44

标签: php curl

我尝试在第一个示例代码中转换找到here的cURL代码。这是他们给我的cURL:

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

这是我到目前为止所做的,而且它无法正常工作:

<?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>";
?>

我在编码的行中包含了一些其他尝试。我已经尝试过查看php cURL文档,但我无法想出这个。

提前致谢。

1 个答案:

答案 0 :(得分:1)

以下是curl命令的直接翻译,我注意到的唯一主要区别是标题位于数组中并将CURLOPT_CUSTOMREQUEST设置为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>";