問題描述
我正在使用具有此功能的 simplehtmldom:
I am making use of simplehtmldom which has this funciton:
// 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 和 catch ,但這沒有用,因為它沒有拋出異常,它只是給出了這樣的 php 警告:
Sometimes, a URL may just not be valid and I want to handle this. I thought I could use a try and catch but this hasn't worked since it doesn't throw an exception, it just gives a php warning like this:
[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 行在上面的代碼中.
Line 39 is in the above code.
我如何正確處理這個錯誤,我可以只使用一個簡單的 if
條件,它看起來不像返回一個布爾值.
How can i correctly handle this error, can I just use a plain if
condition, it doesn't look like it returns a boolean.
感謝大家的幫助
這是一個好的解決方案嗎?
Is this a good solution?
if(fopen(urlencode(trim("$next_url")), 'r')){
$html3 = file_get_html(urlencode(trim("$next_url")));
}else{
//do other stuff, error_logging
return false;
}
推薦答案
這里有一個想法:
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
本身,您可以
Basically a wrapper to file_get_contents
. It will throw an exception on failure.
To avoid having to override file_get_contents
itself, you can
// change this
$dom->load(call_user_func_array('file_get_contents', $args), true);
// to
$dom->load(call_user_func_array('fget_contents', $args), true);
現(xiàn)在您可以:
try {
$html3 = file_get_html(trim("$link"));
} catch (Exception $e) {
// handle error here
}
錯誤抑制(通過使用 @
或降低 error_reporting 級別是一個有效解決方案.這可能會引發(fā)異常,您可以使用它來處理您的錯誤.有file_get_contents
可能產(chǎn)生警告的原因有很多,PHP 的手冊本身建議降低 error_reporting:參見手冊
Error suppression (either by using @
or by lowering the error_reporting level is a valid solution. This can throw exceptions and you can use that to handle your errors. There are many reasons why file_get_contents
might generate warnings, and PHP's manual itself recommends lowering error_reporting: See manual
這篇關(guān)于使用 file_get_contents 進行良好的錯誤處理的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!