file_get_contents处理错误的好方法

Has*_*100 11 html php

我试图错误处理file_get_contents方法,所以即使用户输入一个不正确的网站,它将回显一条错误消息而不是非专业

警告:file_get_contents(sidiowdiowjdiso):无法打开流:第6行的C:\ xampp\htdocs\test.php中没有此类文件或目录

我想如果我试一试并抓住它将能够捕获错误,但这不起作用.

try  
{  
$json = file_get_contents("sidiowdiowjdiso", true); //getting the file content
}  
catch (Exception $e)  
{  
 throw new Exception( 'Something really gone wrong', 0, $e);  
}  
Run Code Online (Sandbox Code Playgroud)

And*_*olk 12

使用curl_error而不是file_get_contents 尝试cURL :

<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = '';
if( ($json = curl_exec($ch) ) === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    echo 'Operation completed without any errors';
}

// Close handle
curl_close($ch);
?>
Run Code Online (Sandbox Code Playgroud)

  • 因为这不是OP关于使用file_get_contents()的问题的答案 - 提供替代方案并不是真正的解决方案.OP询问如何处理来自file_get_contents()的错误和警告,而不是如何以完全不同的方式处理错误和警告.请注意,cURL不是PHP的file_get_contents()的替代品,任何进行此移动的人都必须严格重构他们的代码,因此这不是一个可接受的答案. (16认同)

m4t*_*1t0 7

file_get_contents 不要抛出异常,而是返回false,这样你就可以检查返回的值是否为false:

$json = file_get_contents("sidiowdiowjdiso", true);
if ($json === false) {
    //There is an error opening the file
}
Run Code Online (Sandbox Code Playgroud)

这样你仍然会收到警告,如果你想删除它,你需要把它@放在前面file_get_contents.(这被认为是一种不好的做法)

$json = @file_get_contents("sidiowdiowjdiso", true);
Run Code Online (Sandbox Code Playgroud)

  • 讨论[error_reporting()](http://uk1.php.net/manual/en/function.error-reporting.php)可能比推广使用`@`更好. (7认同)

chr*_*d84 5

您可以执行以下任何操作:

为所有未处理的异常设置一个全局错误处理程序(也将处理WARNING):http://php.net/manual/en/function.set-error-handler.php

或者通过检查file_get_contents函数的返回值(使用===运算符,因为它将在失败时返回布尔值false),然后相应地管理错误消息,并通过添加"@"来禁用函数的错误报告像这样:

$json = @file_get_contents("file", true);
if($json === false) {
// error handling
} else {
// do something with $json
}
Run Code Online (Sandbox Code Playgroud)