2010-05-18 17 views
5

En samplexml.svg hay un nodoCómo cambiar el valor del atributo del archivo SVG

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

tengo que sustituir "image1.png" con otro valor como "image2.png". Por favor, guíame con código de ejemplo de cómo hacerlo.

Pude obtener el valor de atributo "image1.png". Aquí está el código:

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

Aquí se samplexml.svg:

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

¿Cómo cambiar mediante programación la xlink: href valor?

Respuesta

-2

Una forma podría ser cargar el archivo como una cadena y luego hacer la búsqueda y reemplazarlo. Luego puede usar loadXML http://www.php.net/manual/en/domdocument.loadxml.php y suministrar la cadena modificada como parámetro.

+3

-1 por sugerir buscar/reemplazar cuando ya está usando el DOM. –

+0

Holy cow, ¿entonces no puedes sugerir mejores alternativas? Relájate amigo. – zaf

+0

Ya me fui [mi propia respuesta] (http://stackoverflow.com/questions/2857113/how-to-change-the-attribute-value-of-svg-file/2857206#2857206). Solo dándole retroalimentación sobre el voto en baja. Cada vez que alguien sugiere buscar/reemplazar datos XML/HTML, Dios mata a un gatito. –

13

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

+1 Para mí aprender algo nuevo hoy. – zaf

Cuestiones relacionadas