2011-12-13 62 views
21

我只是用file_get_contents()擺脫這樣的用戶的最新微博:的file_get_contents拋出400錯誤請求錯誤PHP

$tweet = json_decode(file_get_contents('http://api.twitter.com/1/statuses/user_timeline/User.json')); 

這工作在我的本地正常,但當我把它上傳到我的服務器時,它引發此錯誤:

Warning: file_get_contents(http://api.twitter.com/1/statuses/user_timeline/User.json) [function.file-get-contents]:failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request...

不知道什麼可能導致它,也許一個PHP配置我需要我的服務器上設置?

在此先感謝!

+0

閱讀:http://stackoverflow.com/questions/697472/file-get-contents-returning-failed-to-open-stream-http-request-failed –

+2

請參見[這堆問題] [1],因爲它可能會回答你的問題。 [1]:http://stackoverflow.com/questions/3710147/php-get-content-of-http-400-response –

+0

感謝彼得·布魯克斯!這工作! – javiervd

回答

23

您可能想嘗試使用curl來檢索數據而不是file_get_contents。捲曲有錯誤處理的更好的支持:

// make request 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://api.twitter.com/1/statuses/user_timeline/User.json"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 

// convert response 
$output = json_decode($output); 

// handle error; error output 
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) { 

    var_dump($output); 
} 

curl_close($ch); 

這可能會給你一個更好的主意,爲什麼你收到的錯誤。常見的錯誤是達到服務器上的速率限制。

+1

你應該打印'curl_error($ ch)'以獲得更詳細的錯誤。 –

0

只是本答的一個小附錄。 根據PHP manual,當使用curl_init()初始化cURL句柄時,可以設置CURLOPT_URL選項。

// make request 
$ch = curl_init("http://api.twitter.com/1/statuses/user_timeline/User.json"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 

// convert response 
$output = json_decode($output); 

// handle error; error output 
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) { 

    var_dump($output); 
} 

curl_close($ch);