2010-08-11 156 views
3

使用与simplehtmldom脚本代码(http://simplehtmldom.sourceforge.net/manual.htm):PHP处理错误

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

如何处理错误回报上file_get_html($url)一部分?现在,如果页面不存在,它会在浏览器窗口中显示错误。我更喜欢赶上它们,并显示我的文字,如:

if(some error happened on file_get_html($url)) { 
    $errors = true; 
} else { 
    html = file_get_html($url); 
} 

谢谢。

回答

4

尝试把 try-catch像这样在你的函数:

try{ 
    $dom->load(call_user_func_array('file_get_contents', $args), true); 
    return $dom; 
} 
catch(Exception $e){ 
    //echo $e->getMessage(); 
    throw new Exception('could not load the url'); 
} 

更新:

或者您可以使用此功能查看远程链接确实存在:

function url_exists($url){ 
    if ((strpos($url, "http")) === false) $url = "http://" . $url; 
    if (is_array(@get_headers($url))) 
     return true; 
    else 
     return false; 
} 

这里是你如何使用上述功能:

function file_get_html() { 
    $args = func_get_args(); 

    if (url_exists($args)) { 
     $dom = new simple_html_dom; 
     $dom->load(call_user_func_array('file_get_contents', $args), true); 
     return $dom; 
    } 
    else { 
     echo "The url isn't valid"; 
     return false; 
    } 
} 
+0

请详细介绍catch()部分。 $ e-> getMessage() - 这是什么意思? – James 2010-08-11 13:28:22

+0

似乎不起作用,给出了一个错误(像以前一样):未能打开流:HTTP请求失败! HTTP/1.1 404 Not Found – James 2010-08-11 13:29:45

+2

我认为简单的HTML DOM解析器不会抛出任何异常。 – Gumbo 2010-08-11 13:30:35

6

嗨 您需要检查的404未找到的消息,因为返回在任何情况下的阵列。

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

这工作。干杯拉尔斯。 – 2012-02-21 19:56:34

+0

这有效。谢谢 – trante 2012-03-01 13:17:52