Search code examples
phpxmldomcdata

How to change value of cdata inside a .xml file and then again save it using php


i want to just change ABCD written inside cdata of data.xml file with a new value held by $change by php. i am able to get all cdata value using the following code but don't know how to change and save it.

<?php
$doc = new DOMDocument();
$doc->load('data.xml');
$destinations = $doc->getElementsByTagName("text");
foreach ($destinations as $destination) {
    foreach($destination->childNodes as $child) {
        if ($child->nodeType == XML_CDATA_SECTION_NODE) {
            echo $child->textContent . "<br/>";
        }
    }
}
?>

my data.xml file.

<?xml version="1.0" encoding="utf-8"?>
<data displayWidth="" displayHeight="" frameRate="" fontLibs="assets/fonts/Sansation_Regular.swf">
    <preloader type="snowflake" size="40" color="0xffffff" shapeType="circle" shapeSize="16" numShapes="8"/>
        <flipCard openingDuration="2" openCardZ="400" tweenMethod="easeOut" tweenType="Back">
            <video videoPath="video.MP4" frontImage="assets/christmas/front.jpg" videoPoster="assets/christmas/videoPoster.jpg" videoFrame="assets/christmas/videoFrame.png" bufferTime="10" loopVideo="true"/>
            <flips backImage="assets/christmas/back.jpg" backColor="0x808080">

            <flip isText="true" xPos="600" yPos="470" openDelay="8" openDuration="2" tweenMethod="easeOut" tweenType="Elastic" action="link" url="http://activeden.net/">
                <text id="name" font="Sansation_Regular" embedFonts="true" size="40" color="0x802020"><![CDATA[ABCD]]></text>
            </flip>

            <flip isText="true" xPos="300" yPos="30" openDelay="2" openDuration="2" tweenMethod="easeOut" tweenType="Elastic">
                <text font="Sansation_Regular" embedFonts="true" size="80" color="0x202020"><![CDATA[HAPPY]]></text>
            </flip>
        </flips>
    </flipCard>
</data>

Solution

  • You change the text inside a CDATA section by setting the nodeValue of that CDATA node (DOMCdataSection in PHP):

    $child->nodeValue = $change;
    

    Output (excerpt & simplified):

        ...
            <flip isText="true" xPos="600" yPos="470" openDelay="8" openDuration="2" tweenMethod="easeOut" tweenType="Elastic" action="link" url="http://activeden.net/">
                <text id="name" ... color="0x802020"><![CDATA[changed ABCD]]></text>
            </flip>
    
            <flip isText="true" xPos="300" yPos="30" openDelay="2" openDuration="2" tweenMethod="easeOut" tweenType="Elastic">
                <text font="Sansation_Regular" ... ><![CDATA[changed HAPPY]]></text>
            </flip>
    
        ...
    

    For your second question you have on how to save the document: The method to save the XML document is DOMDocument::save:

    $filename = '/path/to/file.xml';
    $doc->save($filename);