2011-08-26 65 views
0

我有一個PHP腳本是這樣的:curl,如何使用file_get_contents?

<?php 
$likes = 'https://graph.facebook.com/google'; 
$fb = file_get_contents($likes); 
$fb_array=json_decode($fb,true); 
$all_likes = $fb_array['likes']; 
$english_format = number_format($all_likes); 
?> 

有時會發生什麼是該URL失敗,我得到這樣的:

Warning: file_get_contents(https://graph.facebook.com/google) [function.file-get-contents]: failed to open stream: HTTP request failed! in /var/www/html/google/index.php on line 774 

我想知道是否有針對的方式代碼將優雅地降級,因爲我的整個網站都被關閉了。

我在想如果有一個PHP或捲曲替代處理該錯誤。

有什麼想法?

感謝

編輯: 我可以這樣的:

<?php 
$likes = 'https://graph.facebook.com/google'; 
if([email protected]_get_contents($likes)){ 
    $english_format = 123; 
} else { 
$fb = file_get_contents($likes); 
$fb_array=json_decode($fb,true); 
$all_likes = $fb_array['likes']; 
$english_format = number_format($all_likes); 
    } 
?> 

,但它仍然會減慢我的網站

+0

你爲什麼使用錯誤抑制? – NullUserException

回答

1

您可以通過使用stream context處理HTTP錯誤與file_get_contents

$context = stream_context_create(array(
    'http' => array(
     'ignore_errors' => true, 
    ), 
)); 

$fb = file_get_contents('http://www.google.com'); 
$code = substr($http_response_header[0], strpos($http_response_header[0], ' ')+1); 

if ($code != 200) { 
    // there might be a problem 
} 

此外,display_errors應該Off在生產環境中。

-1

你可以設置一個Error Handler趕上(和禮貌管理)的錯誤。

或者,您可以@suppress錯誤,然後在繼續之前檢查以確保$fb有效。

+0

-1批准使用@ @ – NullUserException

+1

@NullUserException:沒有贊同這麼多,因爲它是一個可行的選擇。僅僅因爲它不是最好的選擇,並不意味着它不是一種選擇。它在PHP中,它能夠被[誤]使用。我會親自找到問題的根源或使用自定義錯誤處理程序。 –

+0

@布拉德克里斯蒂,+1。我同意心態。不好的選擇仍然是一個選擇。 :)。保持簡單愚蠢(KISS) – froditus

1

我不喜歡@,因爲這會讓代碼執行變慢。但你可以在下面使用的代碼,因爲如果一切正常,你做兩個的file_get_contents和它的速度慢

$likes = 'https://graph.facebook.com/google'; 
$result = @file_get_contents($likes); 
if(empty($result)){ 
    $english_format = 123; 
} else { 
    $fb_array=json_decode($result,true); 
    $all_likes = $fb_array['likes']; 
    $english_format = number_format($all_likes); 
} 
+0

「我不喜歡@,因爲這會讓代碼執行速度變慢。」 ''' – NullUserException

+0

有一個更大的問題我知道這個問題,但是代碼中的一個原因是調用兩個file_get_contents –

+0

我試過了,它減慢了網站的速度,嗯 – Patrioticcow