【发布时间】:2010-09-18 06:40:46
【问题描述】:
我想使用simple_html_dom.php 从 HTML 文档中删除空段落。我知道如何使用 DOMDocument 类来做到这一点,但是,因为我使用的 HTML 文件是在 MS Word 中准备的,所以 DOMDocument 的 loadHTMLFile() 函数会给出这个异常“未定义命名空间”。
这是我与 DOMDocument 对象一起用于未在 MS Word 中准备的 HTML 文件的代码:
<?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");
?>
这是我与 simple_html_dom.php 模块一起使用的代码,用于在 MS Word 中准备的 HTML 文件:
<?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");
?>
几乎相同,只是$pars变量在使用DOMDocument时是一个DOMNodeList,而在使用simple_html_dom.php时是一个数组。但是这段代码不起作用。首先它运行了两分钟,然后报告了这些错误:“未定义的偏移量:1”和“尝试获取非对象的属性”对于这一行:“if (trim($pars[$i]->plaintext) == "" ) {"。
有谁知道我该如何解决这个问题?
谢谢。
我也在php devnetwork上问过。
【问题讨论】:
-
我猜你发布的第一个代码块中的
if (trim($pars->item($i)->textContent == "")){应该是if (trim($pars->item($i)->textContent) == ""){ -
ps:第二个代码块
if (trim($pars[$i]->plaintext == "")) {=>if (trim($pars[$i]->plaintext) == "") {;) -
@DaNiel,感谢您指出这一点,但在修复它之后,我得到了相同的结果。