How to change the attribute value of svg file

冷暖自知 提交于 2019-12-07 06:13:48

问题


In samplexml.svg there is a node

<image width="744" height="1052" xlink:href="image1.png"/>

I need to replace "image1.png" with another value like "image2.png". Please guide me with sample code how to to that.

I could get the attribute value "image1.png". Here is the code:

$xdoc = new DomDocument;
$xdoc->Load('samplexml.svg');
$tagName = $xdoc->getElementsByTagName('image')->item(0);
$attribNode = $tagName->getAttributeNode('xlink:href');

echo "Attribute Name  : " . $attribNode->name . "<br/>";
echo "Attribute Value : " . $attribNode->value;

Here is samplexml.svg:

<svg>
    <g>
        <title>Test title</title>
        <image x="0" y="0" width="744" height="1052" xlink:href="image1.png"/>
    </g>
</svg>

How do I programmatically change the xlink:href value?


回答1:


Use DOMElement::setAttributeNS():

$xdoc = new DomDocument;
$xdoc->Load('svg.xml');
$tagName = $xdoc->getElementsByTagName('image')->item(0);
$attribNode = $tagName->getAttributeNode('xlink:href');

echo "Attribute Name  : " . $attribNode->name . "<br/>";
echo "Attribute Value : " . $attribNode->value;

$tagName->setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'image2.png');

echo $xdoc->saveXML();



回答2:


One way could be to load the file as a string and then do the search and replace on it. You then can use loadXML http://www.php.net/manual/en/domdocument.loadxml.php and supply the changed string as a parameter.



来源:https://stackoverflow.com/questions/2857113/how-to-change-the-attribute-value-of-svg-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!