繁体   English   中英

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

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

我在我的项目中使用PHP Simple HTML DOM Parser库,但是我不知道如何使方法正常工作。

首先,我将字符串转换为DOM对象:

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

$rarr变量是html字符串元素的数组。 我想删除它们的classtitle属性,因此我使用以下代码:

$html = $html->removeAttribute('class');
$html = $html->removeAttribute('title');

但我收到以下错误:

致命错误 :在第198行的/scripts/defios.php中调用未定义的方法simple_html_dom :: removeAttribute()

根据Documentationstr_get_html() 从字符串创建DOM对象。 而且我认为removeAttribute()方法不是DOM方法,而是Element方法,这就是我收到错误的原因。 因此,我需要以某种方式将DOM转换为Element。 我认为find()方法可以完成这项工作,但是问题是我不能使用它,因为数组中的html元素是随机的(有些是div,span,它们没有通用的类或id) ,因此该方法并没有真正帮助我。 DOM本身更多是元素,因此我不想在DOM中选择某些东西,而是将整个DOM转换为Element。

我需要做的就是删除该类和标题,因此将不胜感激。

这是删除这些内容的方法:

foreach($html->find('[class]') as $el) $el->removeAttribute('class');
foreach($html->find('[title]') as $el) $el->removeAttribute('title');

关键是访问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