【问题标题】:Php Simple Html - How to convert the DOM to an ElementPhp Simple Html - 如何将 DOM 转换为元素
【发布时间】:2017-07-11 18:26:59
【问题描述】:

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

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

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

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

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

但我收到以下错误:

致命错误:在 /scripts/defios.php198

中调用未定义方法 simple_html_dom::removeAttribute() >

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

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

【问题讨论】:

  • 您没有发现我的回答有帮助吗?请让我知道如何更好地改进它。谢谢。

标签: php dom simple-html-dom


【解决方案1】:

以下是我删除这些的方法:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 2016-04-09
      • 2023-03-15
      • 2020-02-26
      • 1970-01-01
      • 2010-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多