Last Updated: February 25, 2016
·
457
· 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();

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#php
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside