【发布时间】:2013-10-12 17:30:40
【问题描述】:
我正在使用一个名为 Simple HTML DOM 的库
其中一个方法,将 url 加载到 DOM 对象中:
function load_file()
{
$args = func_get_args();
$this->load(call_user_func_array('file_get_contents', $args), true);
// Throw an error if we can't properly load the dom.
if (($error=error_get_last())!==null) {
$this->clear();
return false;
}
}
为了测试错误处理,我创建了这段代码:
include_once 'simple_html_dom.php';
function getSimpleHtmlDomLoaded($url)
{
$html = false;
$count = 0;
while ($html === false && ($count < 10)) {
$html = new simple_html_dom();
$html->load_file($url);
if ($html === false) {
echo "Error loading url!\n";
sleep(5);
$count++;
}
}
return $html;
}
$url = "inexistent.html";
getSimpleHtmlDomLoaded($url);
这段代码背后的想法是,如果 url 加载失败,再试一次,如果 10 次尝试仍然失败,它应该返回 false。
但是,如果 url 不存在,load_file 方法似乎永远不会返回 false。
相反,我收到以下警告消息:
PHP 警告:file_get_contents(inexisten.html):打开流失败
知道如何解决这个问题吗?
注意:我最好避免入侵图书馆。
【问题讨论】:
-
警告有什么问题?是有警告还是不能检查加载文件是否有问题?此外(只是提示)PHP 有一个可用的 DomDocument,它比“简单的 HTML DOM”库要好得多。见How to parse and process HTML with PHP?
标签: php error-handling simple-html-dom