如何在.xml文件中更改cdata的值,然后再使用php保存它

时间:2014-12-31 09:55:49

标签: php xml dom cdata

我想改变在data.xml文件的cdata中写入的ABCD,其中包含由$ change更改的新值。我可以使用以下代码获取所有cdata值,但不知道如何更改和保存它。

<?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/>";
        }
    }
}
?>

我的data.xml文件。

<?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>

2 个答案:

答案 0 :(得分:3)

通过设置该CDATA节点的nodeValueDOMCdataSection in PHP)来更改CDATA部分内的文本:

$child->nodeValue = $change;

输出(摘录和简化):

    ...
        <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>

    ...

关于如何保存文档的第二个问题:保存XML文档的方法是DOMDocument::save

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

答案 1 :(得分:1)

来自@Hakre的回答是正确的。只想更新最终的工作代码,因为下面的代码只会更新我的ABCD值。

<?php
$doc = new DOMDocument();
$xml='data.xml';
$doc->load($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/>";
            $child->nodeValue = "new value";
        }
    }break;
}
$doc->save($xml);
?>