dongzha2525 2012-11-21 05:19
浏览 45
已采纳

使用PHP DOMDocument替换XML节点的非文本

I want to replace innertext of a XML node my XML file named test.xml is

<?xml version="1.0" encoding="utf-8"?>
<ads>
    <loop>no</loop>
    <item>
        <description>Description 1</description>
    </item>
    <item>
        <description>Text in item2</description>
    </item>
    <item>
        <description>Let play with this XML</description>
    </item>
</ads>

I want to change the value of loop and description tag both, and it should be saved in test.xml like:

<?xml version="1.0" encoding="utf-8"?>
<ads>
    <loop>yes</loop>
    <item>
        <description>Description Changing Here</description>
    </item>
    <item>
        <description>Changing text in item2</description>
    </item>
    <item>
        <description>We will play later</description>
    </item>
</ads>

I tried code in PHP:

<?
    $file = "test.xml";
    $fp = fopen($file, "rb") or die("cannot open file");
    $str = fread($fp, filesize($file));
    $dom=new DOMDocument();
    $dom->formatOutput = true;
    $dom->preserveWhiteSpace = false;
    $dom->loadXML($str) or die("Error");
    //$dom->load("items.xml");

    $root=$dom->documentElement; // This can differ (I am not sure, it can be only documentElement or documentElement->firstChild or only firstChild)

    $loop=$root->getElementsByTagName('loop')->item(0);//->textContent;
    //echo $loop;
    if(trim($loop->textContent)=='no')
    {
        echo 'ok';
        $root->getElementsByTagName('loop')->item(0)->nodeValue ='yes';
    }
    echo "<xmp>NEW:
". $dom->saveXML() ."</xmp>";
?>

I tried only for loop tag.I don't know how to replace nodevalue in description tag. When I run this page it shows output like:

ok
NEW:
<?xml version="1.0" encoding="utf-8"?>
<ads>
    <loop>yes</loop>
    <item>
        <description>Description 1</description>
    </item>
    <item>
        <description>Changing text in item2</description>
    </item>
    <item>
        <description>Let play with this XML</description>
    </item>
</ads>

It gives the value yes in browser but don't save it in test.xml any reason?

  • 写回答

1条回答 默认 最新

  • duanshaiduhao2471 2012-11-21 06:33
    关注

    So, since you have created DOMDocument you can use DOMXpath. Or keep using getElementsByTagName()

    You could do this (but only in that context):

    $descriptions = $root->getElementsByTagName('description');
    foreach($descriptions as $nodeDesciption)
    {
        $nodeDesciption->nodeValue ='Your custom value';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b