snecserc
snecserc

Reputation: 615

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.

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.

Upvotes: 0

Views: 489

Answers (2)

pguardiario
pguardiario

Reputation: 54984

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');

Upvotes: 2

MackProgramsAlot
MackProgramsAlot

Reputation: 593

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');
    }

Upvotes: 1

Related Questions