2011-12-13 33 views
21

Tôi chỉ sử dụng một file_get_contents() để có được những tweet mới nhất từ ​​một người sử dụng như thế này:file_get_contents ném 400 Bad Request lỗi PHP

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

này hoạt động tốt trên localhost của tôi, nhưng khi tôi tải nó lên máy chủ của tôi nó ném lỗi này:

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...

Không chắc chắn điều gì có thể gây ra, có thể cấu hình php tôi cần đặt trên máy chủ của mình?

Cảm ơn trước!

+0

đọc: http://stackoverflow.com/questions/697472/file-get-contents-returning-failed-to-open-stream-http-request-failed –

+2

Vui lòng xem [đống này câu hỏi] [1] vì nó có thể sẽ trả lời câu hỏi của bạn. [1]: http://stackoverflow.com/questions/3710147/php-get-content-of-http-400-response –

+0

Cảm ơn Peter Brooks! Điều đó đã hiệu quả! – javiervd

Trả lời

23

Bạn có thể muốn thử sử dụng curl để truy xuất dữ liệu thay vì tệp_get_contents. curl có hỗ trợ tốt hơn để xử lý lỗi:

// 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); 

Điều này có thể giúp bạn hiểu rõ hơn tại sao bạn gặp lỗi. Lỗi phổ biến là đạt đến giới hạn tốc độ trên máy chủ của bạn.

+1

Bạn nên in 'curl_error ($ ch)' để có lỗi chi tiết hơn. –

0

Chỉ cần một chút phụ lục về câu trả lời của Ben. Theo PHP manual tùy chọn CURLOPT_URL có thể được đặt khi inizializing xử lý cURL với curl_init().

// 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); 
2

Bạn có thể sử dụng file_get_contents thêm ignore_errors tùy chọn thiết lập để true, bằng cách này bạn sẽ nhận được toàn bộ cơ thể của phản ứng trong trường hợp lỗi (HTTP/1.1 400, ví dụ) và không chỉ là một đơn giản false .

Bạn có thể thấy một ví dụ ở đây: https://stackoverflow.com/a/11479968/3926617

Nếu bạn muốn truy cập vào tiêu đề phản ứng, bạn có thể sử dụng $http_response_header sau khi yêu cầu.

http://php.net/manual/en/reserved.variables.httpresponseheader.php

Các vấn đề liên quan