Update XML node attribute

87 views Asked by At

I'm trying the following without success. Anyone who can help me out about why the attribute imageId is not changed?

$dom = new DOMDocument;
$dom->loadXML($appCom_file_name);
$frames = $dom->getElementsByTagName('frame');
foreach ($frames as $frame) {
    if ($frame->getAttribute('imageId') == '') {
        $frame->setAttribute('imageId', $id);
    } 
}

$dom->saveXML();

XML source:

<template>
    <appCom>
        <page>
            <defaultValues>
                <frame id="frame_01_0" deltaRotation="0" deltaScale="100" deltaX="0" deltaY="0" imageId="" />
                <frame id="frame_02_0" deltaRotation="0" deltaScale="100" deltaX="0" deltaY="0" imageId="" />
                <frame id="frame_03_0" deltaRotation="0" deltaScale="100" deltaX="0" deltaY="0" imageId="" />
            </defaultValues>
        </page>
        <page>
            <defaultValues>
                <frame id="frame_01_1" deltaRotation="0" deltaScale="100" deltaX="0" deltaY="0" imageId="" />
                <frame id="frame_02_1" deltaRotation="0" deltaScale="100" deltaX="0" deltaY="0" imageId="" />
                <frame id="frame_03_1" deltaRotation="0" deltaScale="100" deltaX="0" deltaY="0" imageId="" />
            </defaultValues>
        </page>
    </appCom>
</template>
3

There are 3 answers

1
jxe On BEST ANSWER

Thanks for all feeback!

It should not output anything but save the file again. ID was of course defined but I forgot to include it with my question. This works now:

$id = 1;

$dom = new DOMDocument;
$dom->loadXML(file_get_contents($appCom_file_name));
$frames = $dom->getElementsByTagName('frame');
foreach ($frames as $frame) {
    if ($frame->getAttribute('imageId') == '') {
        $frame->setAttribute('imageId', $id);
    } 
}

$dom->save($appCom_file_name);
0
Martin Hrabal On

I think you must use saveXML with parametr... here is my code for inspiration:

$dom = new DOMDocument();
$dom->loadXML($datas);

$svg = $dom->getElementsByTagName('svg');                        
$resize = $this->resize(452, 480, $res);
$svg->item(0)->setAttribute('width', $resize['w']);  
$svg->item(0)->setAttribute('height', $resize['h']); 
$datas = '<?xml version="1.0" encoding="UTF-8" tandalone="no"?>'.$dom->saveXML($svg->item(0));
0
silkfire On

I tested your code and obviously, I'm getting an error that $id is not defined. Have you tried changing this line:

$frame->setAttribute('imageId', $id);

to this:

$frame->setAttribute('imageId', $frame->getAttribute('id'));

?

And of course, to print the results to the screen you would use echo:

echo $dom->saveXML();