tags:

views:

16

answers:

1

I want to alter the class attribute of an image tag in PHP. I could do it using regex but want to use DOM / SimpleXML. The simplexml element looks like this:

$obj = simplexml_load_string($unprocessedfield);
var_dump($obj->img);

object(SimpleXMLElement)#108 (1) { 
    ["@attributes"]=>  array(6) { 
        ["class"]=>  string(33) "alignnone size-full wp-image-5499" 
        ["title"]=>  string(22) "Image: credit" 
        ["src"]=>  string(28) "/files/2010/09/laser-338.jpg" 
        ["alt"]=>  string(0) "" 
        ["width"]=>  string(3) "338" 
        ["height"]=>  string(3) "338" 
    } 
} 

I want to add to the class attribute but can't seem to access the individual elements of that array e.g. var_dump($obj->img->attributes['class']) gives me NULL.

thanks for any pointers.

A: 

I am not sure if this would work, but you could try the SimleXML->addAtribute() method and just add an atribute with the same name. In theory, it should overwrite the current attribute. But other than that I do not see a method to modify attributes through the manual.

Perhaps the PHP DOM's DOMElement::setAttribute() might work if the simpleXML one does not.

Brad F Jacobs
Thanks. I sorted it with $obj->img['class'] .= ' corner iradius10';
codecowboy
Glad to hear and thanks for posting the solution you found!
Brad F Jacobs