我想用 PHP $change持有的新值更改写入 cdata of data.xml 文件中的 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/>";
}
}
}
?>
我的数据.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 节点(PHP 中的 DOMCdataSection )的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);
@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);
?>