2012-09-20 39 views
3

如何发送PHP中提到的CURL请求?我将在PHP中使用哪些函数?如何在PHP中使用curl将访问密钥作为HTTP标头传递

$ curl -H 'X-Sifter-Token: 343b1b831066a40e308e0af92e0f06f0' \ 
-H 'Accept: application/json' \ 
'http://example.sifterapp.com/api/projects' 

我已经试过这个代码..但它不工作.. 请做要紧

$curlString = ""; 

$curlString .= "-H \"X-Sifter-Token: 343b1b831066a40e308e0af92e0f06f0\" \"; 

$curlString .= "-H \"Accept: application/json\" \"; 

$url="http://example.sifterapp.com/api/projects"; 


$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_TIMEOUT, 60); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlString); 
$data = curl_exec($ch); 
if (curl_errno($ch)) { 
print "Error: " . curl_error($ch); 
} else { 
// Show me the result 
var_dump($data); 
curl_close($ch); 
} 

回答

6

你不正确使用CURLOPT_HTTPHEADER。从手册:

http://php.net/manual/en/function.curl-setopt.php

CURLOPT_HTTPHEADER HTTP头字段设置的阵列,在 格式array('Content-type: text/plain', 'Content-length: 100')

所以你需要:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
     'X-Sifter-Token: 343b1b831066a40e308e0af92e0f06f0', 
     'Accept: application/json', 
)); 
+0

谢谢期待你的答复。它完成了CURL请求。但我得到'301永久移动'的消息。当我使用var_dump($ response)时,我得到了字符串(184)。什么所有其他的PHP CURL函数我需要用来完成这个请求。我是第一次这样做。 – DeDav

+0

HTTP 301可能意味着您的请求*微调*关闭,例如你问'projects'而不是'projects /'。你可以通过cURL输出所有标题来检查。修复请求更高效;但您可能可以让cURL自动重试,并选择遵循重定向(请参阅setopt手册页)。 – LSerni

相关问题