Php Simple Html - 如何将DOM转换为元素
I'm using PHP Simple HTML DOM Parser
library in my project, but I can't figure out how to make a method working.
First I convert a string into a DOM object:
$html = str_get_html($rarr[$i]);
the $rarr
variable is an array of html string elements. I want to remove their class
and title
attributes, so I use the following code:
$html = $html->removeAttribute('class');
$html = $html->removeAttribute('title');
but I get the following error:
Fatal error: Call to undefined method simple_html_dom::removeAttribute() in /scripts/defios.php on line 198
According to Documentation, the str_get_html()
Creates a DOM object from a string. and I think the removeAttribute()
method is not a DOM method but an Element method and that's why I get the error. So I need to convert somehow the DOM to Element. I think the find()
method would do the job, but the problem is that I can't use it because the html elements in the array are randomly (some are divs, spans and they don't have a common class or id), so the method doesn't really help me. More the DOM itself is the element so I do not want to select something inside the DOM but to convert the entire DOM to an Element.
All I need to do is to remove that class and title, so any help would be appreciated.
我在我的项目中使用 首先我将字符串转换为DOM对象: p>
但是我收到以下错误 : p>
致命错误 strong>:在 /scripts/defios.php中调用未定义的方法simple_html_dom :: removeAttribute() strong >在线 198 strong> p>
blockquote>
根据文档, 我需要做的就是删除该类和 标题,所以任何帮助将不胜感激。 p>
div> PHP Simple HTML DOM Parser code>库,但我可以 弄清楚如何使方法有效。 p>
$ html = str_get_html ($ rarr [$ i]);
code> pre>
$ rarr code>变量是一个html字符串元素数组。 我想删除他们的
class code>和
title code>属性,所以我使用以下代码: p>
$ html = $ html - > removeAttribute('class');
$ html = $ html-> removeAttribute('title');
code> pre>
str_get_html() code> 从字符串创建一个DOM对象。 em>我认为
removeAttribute() code>方法不是DOM方法,而是Element方法,这就是我得到错误的原因。 所以我需要以某种方式将DOM转换为Element。 我认为
find() code>方法可以完成这项工作,但问题是我无法使用它,因为数组中的html元素是随机的(有些是div,spans,它们不是 有一个共同的类或id),所以这个方法并没有真正帮助我。 DOM本身就是元素,所以我不想在DOM中选择一些内容,而是将整个DOM转换为元素。 p>
Here's how I would remove those:
foreach($html->find('[class]') as $el) $el->removeAttribute('class');
foreach($html->find('[title]') as $el) $el->removeAttribute('title');
The key is to access the children attribute: Take a look at the following example and tweak it to work!
$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');
}