costa
costa

Reputation: 1087

PHP DOMDocument remove tag attribute

I'm having a problem removing attributes from the HTML tags

    $content = '<span lang="en" xml:lang="en">test</span>';

    $dom = new DOMDocument;
    $dom->loadHTML($content, LIBXML_HTML_NOIMPLIED);
    $nodes = $dom->getElementsByTagName('*');

    foreach($nodes as $node)
    {
        if ($node->hasAttribute('lang'))
        {
            $node->removeAttribute('lang');
        }

        if ($node->hasAttribute('xml:lang'))
        {
            $node->removeAttribute('xml:lang');
        }
    }

    echo $dom->saveHTML($dom->documentElement);

But the result keeps coming

    <span xml:lang="en">test</span>

Why only removes the lang attribute and don't remove the xml:lang="en"? Any ideas?

Upvotes: 1

Views: 937

Answers (1)

Tomasz Winter
Tomasz Winter

Reputation: 287

Probably xml:lang="en" is not corrected value of attribute in html. Change these lines:

$dom->loadHTML($content, LIBXML_HTML_NOIMPLIED);
//code...
echo $dom->saveHTML($dom->documentElement);

to

$dom->loadXML($content, LIBXML_HTML_NOIMPLIED);
//code...
echo $dom->saveXML($dom->documentElement);

Upvotes: 1

Related Questions