程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用file_get_contents进行良好的错误处理大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用file_get_contents进行良好的错误处理?

开发过程中遇到使用file_get_contents进行良好的错误处理的问题如何解决?下面主要结合日常开发的经验,给出你关于使用file_get_contents进行良好的错误处理的解决方法建议,希望对你解决使用file_get_contents进行良好的错误处理有所启发或帮助;

这是一个主意:

function fget_contents() {
    $args = func_get_args();
    // the @ can be removed if you lower error_reporTing level
    $contents = @call_user_func_array('file_get_contents', $args);

    if ($contents === falsE) {
        throw new Exception('Failed to open ' . $filE);
    } else {
        return $contents;
    }
}

基本上是的包装器file_get_contents。失败将引发异常。为了避免不得不覆盖file_get_contents自身,您可以

// change this
$dom->load(call_user_func_array('file_get_contents', $args), truE); 
// to
$dom->load(call_user_func_array('fget_contents', $args), truE);

现在你可以:

try {
    $HTML3 = file_get_HTML(trim("$link")); 
} catch (Exception $E) {
    // handle error here
}

错误抑制(通过使@或通过降低error_reporTing级别是一种 解决方案。这可能引发异常,您可以使用它来处理错误。有很多原因file_get_contents可能会生成警告,php手册本身建议降低error_reporTing:请参见手册

解决方法

我正在使用具有以下功能的simplehtmldom:

// get html dom form file
function file_get_html() {
    $dom = new simple_html_dom;
    $args = func_get_args();
    $dom->load(call_user_func_array('file_get_contents',$args),truE);
    return $dom;
}

我这样使用它:

$html3 = file_get_html(urlencode(trim("$link")));

有时,URL可能只是无效的,我想对此进行处理。我以为我可以使用try and catch,但是这没有用,因为它不会抛出异常,它只是给出了这样的php警告:

[06-Aug-2010 19:59:42] php Warning:  file_get_contents(http://new.mysite.com/ghs 1/) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: http request failed! http/1.1 404 Not Found  in /home/example/public_html/other/simple_html_dom.php on line 39

第39行在上面的代码中。

我如何正确处理此错误,我可以只使用普通if条件,它看起来不像返回布尔值。

谢谢大家的帮助

更新资料

这是一个好的解决方案吗?

if(fopen(urlencode(trim("$next_url")),'r')){

    $html3 = file_get_html(urlencode(trim("$next_url")));

}else{
    //do other stuff,error_logging
    return false;

}

大佬总结

以上是大佬教程为你收集整理的使用file_get_contents进行良好的错误处理全部内容,希望文章能够帮你解决使用file_get_contents进行良好的错误处理所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。