Php 简单 Html - 如何将 DOM 转换为元素
Php Simple Html - How to convert the DOM to an Element
我在我的项目中使用 PHP Simple HTML DOM Parser
库,但我不知道如何使方法起作用。
首先我将一个字符串转换成 DOM object:
$html = str_get_html($rarr[$i]);
$rarr
变量是 html 字符串元素的数组。我想删除它们的 class
和 title
属性,所以我使用以下代码:
$html = $html->removeAttribute('class');
$html = $html->removeAttribute('title');
但出现以下错误:
Fatal error: Call to undefined method simple_html_dom::removeAttribute() in /scripts/defios.php on line 198
根据 Documentation,str_get_html()
从字符串创建 DOM object。 我认为 removeAttribute()
方法不是 DOM 方法,而是 Element 方法,这就是我收到错误的原因。所以我需要以某种方式将 DOM 转换为 Element。我认为 find()
方法可以完成这项工作,但问题是我不能使用它,因为数组中的 html 元素是随机的(有些是 div、span,但它们没有一个常见的 class 或 id),所以这个方法并没有真正帮助我。更多 DOM 本身就是元素,所以我不想 select DOM 内的东西,而是将整个 DOM 转换为一个元素。
我需要做的就是删除 class 和标题,如有任何帮助,我们将不胜感激。
关键是访问 children 属性:查看以下示例并调整它以工作!
$html = str_get_html($rarr[$i]);
foreach($html as $e)
{
$tag = $e->children[0]; // get the outer most element
$tag->removeAttribute('class');
$tag->removeAttribute('title');
}
以下是我将如何删除它们:
foreach($html->find('[class]') as $el) $el->removeAttribute('class');
foreach($html->find('[title]') as $el) $el->removeAttribute('title');
我在我的项目中使用 PHP Simple HTML DOM Parser
库,但我不知道如何使方法起作用。
首先我将一个字符串转换成 DOM object:
$html = str_get_html($rarr[$i]);
$rarr
变量是 html 字符串元素的数组。我想删除它们的 class
和 title
属性,所以我使用以下代码:
$html = $html->removeAttribute('class');
$html = $html->removeAttribute('title');
但出现以下错误:
Fatal error: Call to undefined method simple_html_dom::removeAttribute() in /scripts/defios.php on line 198
根据 Documentation,str_get_html()
从字符串创建 DOM object。 我认为 removeAttribute()
方法不是 DOM 方法,而是 Element 方法,这就是我收到错误的原因。所以我需要以某种方式将 DOM 转换为 Element。我认为 find()
方法可以完成这项工作,但问题是我不能使用它,因为数组中的 html 元素是随机的(有些是 div、span,但它们没有一个常见的 class 或 id),所以这个方法并没有真正帮助我。更多 DOM 本身就是元素,所以我不想 select DOM 内的东西,而是将整个 DOM 转换为一个元素。
我需要做的就是删除 class 和标题,如有任何帮助,我们将不胜感激。
关键是访问 children 属性:查看以下示例并调整它以工作!
$html = str_get_html($rarr[$i]);
foreach($html as $e)
{
$tag = $e->children[0]; // get the outer most element
$tag->removeAttribute('class');
$tag->removeAttribute('title');
}
以下是我将如何删除它们:
foreach($html->find('[class]') as $el) $el->removeAttribute('class');
foreach($html->find('[title]') as $el) $el->removeAttribute('title');