2010-05-18 22 views
5

在samplexml.svg有一個節點如何改變SVG文件的屬性值

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

我需要像「image2.png」另一個值來代替「image1.png」。請用示例代碼指導我如何做到這一點。

我可以得到屬性值「image1.png」。下面是代碼:

$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; 

這裏是samplexml.svg:

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

如何編程方式更改的XLink:href的值?

回答

-2

一種方法是將文件作爲字符串加載,然後執行搜索並替換它。然後,您可以使用loadXML http://www.php.net/manual/en/domdocument.loadxml.php並將更改的字符串作爲參數提供。

+3

-1提示查找/替換。 – 2010-05-18 12:27:14

+0

聖牛,所以你不能建議更好的選擇?放鬆傢伙。 – zaf 2010-05-18 12:29:51

+0

我已經離開[我自己的答案](http://stackoverflow.com/questions/2857113/how-to-change-the-attribute-value-of-svg-file/2857206#2857206)。只是給你提供反饋意見。每當有人建議搜索/替換XML/HTML數據時,神會殺死一隻小貓。 – 2010-05-18 12:34:12

13

使用DOMElement::setAttributeNS():當他已經在使用DOM

$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(); 
+0

+1對於我今天學習新東西。 – zaf 2010-05-18 12:47:18