我想使用simple_html_dom.php從HTML文檔中刪除空白段落。我知道如何使用DOMDocument類來完成它,但是,由於我使用的HTML文件是在MS Word中準備的,因此DOMDocument的loadHTMLFile()函數會給出此例外「名稱空間未定義」。如何使用simple_html_dom.php從HTML文件中刪除空段落?
這是我與DOMDocument對象爲HTML使用代碼的文件未在MS Word製備:
<?php
/* Using the DOMDocument class */
/* Create a new DOMDocument object. */
$html = new DOMDocument("1.0", "UTF-8");
/* Load HTML code from an HTML file into the DOMDocument. */
$html->loadHTMLFile("HTML File With Empty Paragraphs.html");
/* Assign all the <p> elements into the $pars DOMNodeList object. */
$pars = $html->getElementsByTagName("p");
echo "The initial number of paragraphs is " . $pars->length . ".<br />";
/* The trim() function is used to remove leading and trailing spaces as well as
* newline characters. */
for ($i = 0; $i < $pars->length; $i++){
if (trim($pars->item($i)->textContent) == ""){
$pars->item($i)->parentNode->removeChild($pars->item($i));
$i--;
}
}
echo "The final number of paragraphs is " . $pars->length . ".<br />";
// Write the HTML code back into an HTML file.
$html->saveHTMLFile("HTML File WithOut Empty Paragraphs.html");
?>
這是我與在MS Word製備的HTML文件的模塊simple_html_dom.php使用的代碼:
<?php
/* Using simple_html_dom.php */
include("simple_html_dom.php");
$html = file_get_html("HTML File With Empty Paragraphs.html");
$pars = $html->find("p");
for ($i = 0; $i < count($pars); $i++) {
if (trim($pars[$i]->plaintext) == "") {
unset($pars[$i]);
$i--;
}
}
$html->save("HTML File without Empty Paragraphs.html");
?>
這幾乎是一樣的,不同之處在於,所述$收杆變量是使用DOM文檔時的DOMNodeList和陣列使用simple_html_dom.php時。但是這個代碼不起作用。首先運行兩分鐘,然後報告這些錯誤:「未定義的偏移量:1」和「嘗試獲取非對象的屬性」:「if(trim($ pars [$ i] - > plaintext)==」「 ){「。
有誰知道我該如何解決這個問題?
謝謝。我也問了php devnetwork。
我猜行'如果(修剪($ pars->項目($ I) - >的textContent == 「」))在第{'你需要發佈的代碼塊應該是if(trim($ pars-> item($ i) - > textContent)==「」){' – Strae 2010-09-18 09:16:33
ps:在第二個代碼塊中相同if(trim($ pars [$ i ] - > plaintext ==「」)){'=> if(trim($ pars [$ i] - > plaintext)==「」){';) – Strae 2010-09-18 09:17:37
@DaNiel,謝謝你指出,修復它,我得到相同的結果。 – systemovich 2010-09-19 20:25:16