gpt4 book ai didi

php - 如何使用 simple_html_dom.php 从 HTML 文件中删除空段落?

转载 作者:行者123 更新时间:2023-11-28 00:28:38 26 4
gpt4 key购买 nike

我想使用 simple_html_dom.php 从 HTML 文档中删除空段落.我知道如何使用 DOMDocument 类来做到这一点,但是,因为我使用的 HTML 文件是在 MS Word 中准备的,DOMDocument 的 loadHTMLFile() 函数给出了这个异常“命名空间未定义”。

这是我对未在 MS Word 中准备的 HTML 文件使用 DOMDocument 对象的代码:

<?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时是一个数组。但是这段代码不起作用。首先它运行两分钟然后报告这些错误:“Undefined offset: 1”和“Trying to get property of nonobject”这一行:“if (trim($pars[$i]->plaintext) == “” ) {".

有谁知道我该如何解决这个问题?

谢谢。

我还在 php devnetwork 上问过.

最佳答案

查看 Simple HTML DOM Parser 的文档,我认为这应该可以解决问题:

include('simple_html_dom.php');

$html = file_get_html('HTML File With Empty Paragraphs.html');
$pars = $html->find('p');

foreach($pars as $par)
{
if(trim($par->plaintext) == '')
{
// Remove an element, set it's outertext as an empty string
$par->outertext = '';
}
}

$html->save('HTML File without Empty Paragraphs.html');

我做了一个快速测试,这对我有用:

include('simple_html_dom.php');

$html = str_get_html('<html><body><h1>Test</h1><p></p><p>Test</p></body></html>');
$pars = $html->find("p");

foreach($pars as $par)
{
if(trim($par->plaintext) == '')
{
$par->outertext = '';
}
}

echo $html;
// Output: <html><body><h1>Test</h1><p>Test</p></body></html>

关于php - 如何使用 simple_html_dom.php 从 HTML 文件中删除空段落?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3740660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com