2012-09-24 78 views
0

我使用一個庫中的URL稱爲簡單的HTML DOM錯誤處理加載

一個它的方法,中加載的網址爲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); 

這段代碼背後的想法是要再試一次,如果輸入的網址無法加載,如果經過10個attemps還是失敗,它應返回false。

但是,似乎沒有一個url,load_file方法永遠不會返回false。

相反,我得到以下警告消息:

PHP的警告:的file_get_contents(inexisten.html):未能打開流

任何想法如何解決這一問題?

注意:最好我想避免入侵圖書館。

+0

警告的問題是什麼?是否存在警告或者您無法檢查加載文檔時是否出現問題?另外(只是一個提示)PHP有一個DomDocument,比「簡單的HTML DOM」庫好得多。請參見[如何使用PHP分析和處理HTML?](http://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php) – hakre

回答

2

更改下面的代碼:

$html->load_file($url); 
if ($html === false) { 

這一個:

$ret = $html->load_file($url); 
if ($ret === false) { 

,因爲你檢查對象實例,而不是從load_file()方法返回的值。

0

通過在方法調用之前添加@符號,可以抑制任何警告。如果您使用此功能,請務必像現在一樣自行檢查錯誤,並且確保沒有其他方法可用來確保不會出現警告和/或錯誤。

如果該值等於FALSE而不是對象實例$ html,則應該檢查由load()方法保存在某處的實際數據。

+0

正如您正確指出的那樣,使用@標誌警告會得到抑制,但這不是我想解決的問題。問題是,我似乎無法檢測到URL加載失敗以處理錯誤。 – rfc1484

+0

@ rfc1484擴展了我的答案。 – zeebonk

+0

我剛剛提出了你的答案(以前的downvote不是我的),現在你的解決方案似乎也是正確的。 – rfc1484