Tag Archives: saveXML()

How to change the attribute value of a node in svg (or xml) file by php

Recently I have faced a problem on changing the attribute value of an svg file. At last found a solution.

Lets say an svg file sample.svg:

<svg width="744" height="1052" xmlns="http://www.w3.org/2000/svg" xmlns:se="http://svg-edit.googlecode.com" xmlns:xlink="http://www.w3.org/1999/xlink">
	<g>
		<title>Test Title</title>
		<image x="0" y="0" width="744" height="1052" id="svg_1" xlink:href="image1.png" />
	</g>
</svg>

Now, I want to replace image1.png with image2.png. Here is the code:

<?php
$xdoc = new DomDocument;
$xdoc->Load('sample.svg');

$tagName = $xdoc->getElementsByTagName('image')->item(0);
$attribNode = $tagName->getAttributeNode('xlink:href');
$tagName->setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'image2.png');
$newFileContent = $xdoc->saveXML();

$fh = fopen('sample.svg', 'w') or die("can't open file");
fwrite($fh, $newFileContent);
fclose($fh);
?>

Reff:
setAttributeNS(), saveXML()

Advertisements