开发者

How to add an attribute to an HTML string using DOM/SimpleXML

开发者 https://www.devze.com 2023-01-17 00:06 出处:网络
I want to alter the class attribute of an image tag in PHP. I could do it using regex but want to useDOM / SimpleXML. The simplexml element looks like this:

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"]=>  str开发者_C百科ing(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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消