Last Updated: February 25, 2016
·
300
· teknonono

Replace img alt using DOM

Just input your html code for parsing img > alt; then you'll see the output as your newly replaced alt values:

libxml_use_internal_errors(true);
$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . $html);
$xp = new DOMXPath($doc);
foreach ($xp->query('//img') as $node) {
        $old_alt = $node->getAttribute('alt');
        $new_alt = 'Your new alt attribute value';
        $node->setAttribute('alt', $new_alt);   
}

echo $doc->saveHTML();