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");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件