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

标签 php xml dom cdata

我只想用 php 的 $change 保存的新值更改 data.xml 文件的 cdata 中写入的 ABCD。我可以使用以下代码获取所有 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>

最佳答案

您可以通过设置 CDATA 节点 ( DOMCdataSection in PHP ) 的 nodeValue 来更改 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);

关于php - 如何更改 .xml 文件中 cdata 的值,然后再次使用 php 保存它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27719356/

相关文章:

php - 如何使用 join 进行 where 查询

android - 如何在android中的xml中制作一个具有两种颜色的可绘制矩形?

javascript - 函数 'onclick' 只工作一次

javascript - 用其内容替换父元素

php - 如何在phpmyadmin中更新表中多行的特定字段数据

php - ON DUPLICATE KEY UPDATE 值为 0

php参数传递

c - 无法在 xml 中获取 Soap 响应的根节点

xml - 删除元素中的空命名空间声明

jquery - 需要用jquery将h3和div包装在包装器div中