2011-08-26 64 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