Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add class to an img object in DOM,PHP?

Tags:

dom

php

Here is piece of code

$doc = new DOMDocument();
$doc->loadHTML($article_header);

$imgs = $doc->getElementsByTagName('img');
foreach ($imgs as $img) {

Into $imgs goes DOM img tag. Now I want to change the original img tag by adding some class to it.

SO if the $article_header was this:

"some text"...<img src = 'http://some_source'>...some text...

Now I want it to become this:

"some text"...<img class = 'someclass' src = 'http://some_source'>...some text...

UPDATE

I repeat. Start variable is $article_header. So all changes must be done to it.

With my code I just search through $article_header for img tags , finding them putting them into some variables and change them there is ok, but how can I put all changes back to $article_header ???

like image 603
David Avatar asked Aug 14 '11 11:08

David


People also ask

How to use DOMDocument in PHP?

PHP | DOMDocument getElementsByTagName() Function The DOMDocument::getElementsByTagName() function is an inbuilt function in PHP which is used to return a new instance of class DOMNodeList which contains all the elements of local tag name.

How to Add class name HTML?

HTML. Using . add() method: This method is used to add a class name to the selected element.


1 Answers

In your foreach loop, call $img->setAttribute('class', 'someclass');. This should do the trick. See more at http://docs.php.net/manual/en/domelement.setattribute.php

Then you need to save the modified document back using $article_header = $doc->saveXml();.

like image 81
Seldaek Avatar answered Oct 25 '22 22:10

Seldaek