duanbarong4321 2013-04-19 22:52
浏览 21
已采纳

如何使用php重命名XML值?

How do I rename a value in xml using PHP? This is what I've got so far:

<?php
$q = $_GET["q"];
$q = stripslashes($q);

$q = explode('|^', $q);

$old = $q[0];

$dom                     = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput       = true;

$dom->Load("test.xml");

$xpath   = new DOMXPath($dom);    
$query1  = 'channel/item[title="' . $old . '"]/title';
$entries = $xpath->query($query1);

foreach ($entries as $entry) 
{        
    $oldchapter = $entry->parentNode->removeChild($entry);

    $item       = $dom->getElementsByTagName('item');

    foreach ($item as $items) 
    {
        $title = $dom->createElement('title', $q[1]);            
        $items->appendChild($title);            
    }
}    

$dom->save("test.xml");

Basically, what it does is take two titles from a url, the old existing title, and the one the user wants to change it to (so like this oldtitle|^newtitle), and puts them into an array.

What I've tried doing is removing the existing old title, and then making a new title with, using the new title value from the url, but it doesn't seem to be working. Where am I going wrong, or is there an easier way of doing this?

  • 写回答

1条回答 默认 最新

  • douyong1886 2013-04-20 00:03
    关注

    The way to do this is with DOMNode::replaceChild(). The majority of your code is correct, you've just slightly over-complicated some of the DOM stuff.

    Try this:

    <?php
    
        $q = $_GET["q"];
        $q = stripslashes($q);
    
        $q = explode('|^', $q);
    
        $old = $q[0];
    
        $dom                     = new DOMDocument;
    
        // Do this *before* loading the document
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput       = true;
    
        $dom->Load("test.xml");
        $xpath = new DOMXPath($dom);
    
        $query1  = 'channel/item[title="' . $old . '"]/title';
        $entries = $xpath->query($query1);
    
        // This is all you need to do in the loop
        foreach ($entries as $oldTitle) {
            $newTitle = $dom->createElement('title', $q[1]);
            $entry->parentNode->replaceChild($newTitle, $oldTitle);
        }
    
        $dom->save("test.xml");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程