普通网友 2016-01-12 14:57
浏览 13

用php替换xml元素

I want the peter element replace to other element I Input It.I try to use replace()but it not work.I don't know my code is that right or wrong. I hope have someone to fix my problem.Thx

This is the XML code:

<?xml version="1.0" encoding="UTF-8"?>
<document>   
<information>
    <name>peter</name>
</information>
</document>

This is the PHP code:

<html>
    <head>
    </head>
    <body>
        <form action="index.php" method="POST">                
            Name:<input type="text" name="name"/><br/>
             <input type="submit" name="ok" value="add" /><br>
            <input type="submit" name="check" formaction="read.php" value="check the date" />              
        </form>



        <?php 
        if(isset($_POST['ok'])){
  $xml= new DomDocument("1.0","UTF-8");
  $xml->load("write.xml");

  $rootTag=$xml->getElementsByTagName("document")->item(0);
  $dataTag=$xml->createElement("information");  
  $NameTag= $xml->createElement("name",$_POST['name']);

  $dataTag->appendChild($NameTag); 
  $rootTag->appendChild($dataTag);

  $dataTag->replaceChild($NameTag,$NameTag);


  $xml->formatOutput = true;
  $string_value=$xml->saveXML();
  $xml->save("write.xml");
        }
  ?>
 </body>
</html>
  • 写回答

1条回答 默认 最新

  • duangaoe9401 2016-01-12 16:16
    关注

    I think a possible solution could be to find the current name element, create a new name element, and then use replaceChild to replace the current name element with the new name element:

    For example:

    <html>
    <head>
    </head>
    <body>
    <form action="index.php" method="POST">
        Name:<input type="text" name="name"/><br/>
        <input type="submit" name="ok" value="add"/><br>
        <input type="submit" name="check" formaction="read.php" value="check the date"/>
    </form>
    
    <?php
    if (isset($_POST['ok'])) {
        $xml = new DomDocument("1.0", "UTF-8");
        $xml->load("write.xml");
    
        $currentNameElement = $xml->getElementsByTagName('information')->item(0)->getElementsByTagName('name')->item(0);
        $newNameElement = $xml->createElement("name", $_POST['name']);
        $currentNameElement->parentNode->replaceChild($newNameElement, $currentNameElement);
    
        $xml->formatOutput = true;
        $string_value = $xml->saveXML();
        $xml->save("write.xml");
    }
    ?>
    </body>
    </html>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示