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 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统