简体   繁体   English

PHP简单HTML-如何将DOM转换为元素

[英]Php Simple Html - How to convert the DOM to an Element

I'm using PHP Simple HTML DOM Parser library in my project, but I can't figure out how to make a method working. 我在我的项目中使用PHP Simple HTML DOM Parser库,但是我不知道如何使方法正常工作。

First I convert a string into a DOM object: 首先,我将字符串转换为DOM对象:

$html = str_get_html($rarr[$i]);

the $rarr variable is an array of html string elements. $rarr变量是html字符串元素的数组。 I want to remove their class and title attributes, so I use the following code: 我想删除它们的classtitle属性,因此我使用以下代码:

$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 致命错误 :在第198行的/scripts/defios.php中调用未定义的方法simple_html_dom :: removeAttribute()

According to Documentation , the str_get_html() Creates a DOM object from a string. 根据Documentationstr_get_html() 从字符串创建DOM对象。 and I think the removeAttribute() method is not a DOM method but an Element method and that's why I get the error. 而且我认为removeAttribute()方法不是DOM方法,而是Element方法,这就是我收到错误的原因。 So I need to convert somehow the DOM to Element. 因此,我需要以某种方式将DOM转换为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. 我认为find()方法可以完成这项工作,但是问题是我不能使用它,因为数组中的html元素是随机的(有些是div,span,它们没有通用的类或id) ,因此该方法并没有真正帮助我。 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. DOM本身更多是元素,因此我不想在DOM中选择某些东西,而是将整个DOM转换为Element。

All I need to do is to remove that class and title, so any help would be appreciated. 我需要做的就是删除该类和标题,因此将不胜感激。

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! 关键是访问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');
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM