Pramod Kumar Sharma
Pramod Kumar Sharma

Reputation: 8012

how to edit html in php

I have a string somethink like

   <p><img alt="twerk team" class="pyro-image" src="http://localhost/test/files/thumb/8/595" style="float: none;" /></p>

and what i want to add new string in that

<p><img alt="twerk team" class="pyro-image" src="http://localhost/test/files/thumb/8/595/test_image.jpg" style="float: none;" /></p>

i have tried DOMDocument and Simple HTML parser but not able to do the same. please have a look.

Upvotes: 0

Views: 2343

Answers (1)

MrCode
MrCode

Reputation: 64526

This will append /test_image.jpg to the src of each image element with a class of pyro-image.

Demo

$html = '<p><img alt="twerk team" class="pyro-image" src="http://localhost/test/files/thumb/8/595" style="float: none;" /></p>';

$d = new DOMDocument();
$d->loadHTML($html);

$xp = new DomXPath($d);
$class = 'pyro-image';
$nodes = $xp->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $class ')]");

foreach($nodes as $n)
{
    $n->setAttribute('src', (string)$n->getAttribute('src') . '/test_image.jpg');
    echo $d->saveXML($n->parentNode);

    // note - can use saveHTML() instead but only from PHP 5.3.6
}

Outputs

<p><img alt="twerk team" class="pyro-image" src="http://localhost/test/files/thumb/8/595/test_image.jpg" style="float: none;"/></p>

Upvotes: 1

Related Questions