2014-04-01 40 views
1

我使用的一个网站从他们的IP地址获得用户的国家,但该网站已经关闭了一段时间昨天,造成一吨的问题对我来说。忽略的file_get_contents如果失败

我该如何IGNORE a file_get_contents()如果失败?

这就是我想,但它不能正常工作,还打嗝,如果它不能正常工作:

if($details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"))){ 
    $country = $details->country; 
} 

我看到其他的答案,其说关闭错误报告这对我来说是一个坏的,坏的,坏的想法。

有没有更好的方法或更好的方法来从IP地址获得国家代码?

回答

3

您可以使用stream contextignore_errors选项。

$context = stream_context_create(array('http' => array('ignore_errors' => true))); 
$json = file_get_contents("http://ipinfo.io/{$ip}", false, $context); 

这里的好处是,您还可以看到网站发回给您的错误消息。

+0

不错哦,我忘了那个选项:D –

+0

这比你的cURL解决方案@Jack更好吗?如果是这样,为什么?我只是想接受它。 –

+1

@DarrenSweeney这个答案允许你继续使用'file_get_contents()'几乎不变,所以在这个意义上它更好:)我也删除了我的答案hehe –

0

我觉得这个代码应该没问题:

try{ 
    if($details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"))){ 
    $country = $details->country; 
    } 
} catch(Exception $e) 
{ 
    //log or whatever you want 
} 
+0

没有异常抛出与任何'的file_get_contents()'或'json_decode()'。 –

+0

哎呀我不知道,谢谢 – goto

+0

@goto和杰克,你可以使用一个错误处理程序抛出异常 - 实际上使你的错误的所有(或部分)表现得像个例外。 –

-1

file_get_contents失败时返回假。

$country = "Unknown"; 
if(false !== ($details = json_decode(@file_get_contents("http://ipinfo.io/{$ip}")))){ 
    $country = $details->country; 
} 
if($country !== "Unknown"){ 
    // here you go 
} 
0
if (($cont = file_get_contents("http://ipinfo.io/{$ip}")) && is_object($details = json_decode($cont))) { 
    $country = $details->country; 
}