PHP处理错误

Jam*_*mes 3 php

将此代码与simplehtmldom脚本(http://simplehtmldom.sourceforge.net/manual.htm)一起使用:

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;
}

$url = 'http://site.com/';
$html = file_get_html($url);
Run Code Online (Sandbox Code Playgroud)

如何处理file_get_html($url)部分错误?现在,如果页面不存在,则会在浏览器窗口中显示错误.我喜欢抓住它们并显示我的文字,例如:

if(some error happened on file_get_html($url)) {
   $errors = true;
} else {
   html = file_get_html($url);
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

小智 6

嗨您需要检查404 Not Found消息,因为在任何情况下都返回一个数组.

function url_exists($url){
if ((strpos($url, "http")) === false) $url = "http://" . $url;
$headers = @get_headers($url);
//print_r($headers);
if (is_array($headers)){
    //Check for http error here....should add checks for other errors too...
    if(strpos($headers[0], '404 Not Found'))
        return false;
    else
        return true;    
}         
else
    return false;
}
Run Code Online (Sandbox Code Playgroud)