簡體   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