如何使用PHP更改XML标签名称? [英] How do I change XML tag names with PHP?

查看:218
本文介绍了如何使用PHP更改XML标签名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的XML文件:

I have an XML file that looks something like this:

<product>
<modelNumber>Data</modelNumber>
<salePrice>Data</salePrice>
</product>
 <product>
<modelNumber>Data</modelNumber>
<salePrice>Data</salePrice>
</product>

是否有一种简单的方法可以将标签名称更改为其他名称,例如型号,价格.

Is there a simple way to change the tag names , to something else such as model, price.

从本质上讲,我有一堆包含相似数据但格式不同的XML文件,因此我正在寻找一种简单的方法来解析XML文件,更改某些标签名称并使用更改后的内容编写新的XML文件.标签名称.

Essentially, I have a bunch of XML files containing similar data, but in different formats, so I'm looking for a simple way to parse the XML file, change certain tag names, and write a new XML file with the changed tag names.

推荐答案

下一个功能可以解决问题:

Next function will do the trick:

/**
 * @param $xml string Your XML
 * @param $old string Name of the old tag
 * @param $new string Name of the new tag
 * @return string New XML
 */
function renameTags($xml, $old, $new)
{
    $dom = new DOMDocument();
    $dom->loadXML($xml);

    $nodes = $dom->getElementsByTagName($old);
    $toRemove = array();
    foreach ($nodes as $node)
    {
        $newNode = $dom->createElement($new);
        foreach ($node->attributes as $attribute)
        {
            $newNode->setAttribute($attribute->name, $attribute->value);
        }

        foreach ($node->childNodes as $child)
        {
            $newNode->appendChild($node->removeChild($child));
        }

        $node->parentNode->appendChild($newNode);
        $toRemove[] = $node;
    }

    foreach ($toRemove as $node)
    {
        $node->parentNode->removeChild($node);
    }

    return $dom->saveXML();
}

// Load XML from file data.xml
$xml = file_get_contents('data.xml');

$xml = renameTags($xml, 'modelNumber', 'number');
$xml = renameTags($xml, 'salePrice', 'price');

echo '<pre>'; print_r(htmlspecialchars($xml)); echo '</pre>';

这篇关于如何使用PHP更改XML标签名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆