如何使用PHP更改XML标记名称?

Rya*_*yan 8 php xml

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

<product>
<modelNumber>Data</modelNumber>
<salePrice>Data</salePrice>
</product>
 <product>
<modelNumber>Data</modelNumber>
<salePrice>Data</salePrice>
</product>
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以将标签名称更改为其他内容,例如模型,价格.

本质上,我有一堆XML文件包含类似的数据,但格式不同,所以我正在寻找一种简单的方法来解析XML文件,更改某些标记名称,并用更改的标记名称编写新的XML文件.

小智 8

Kris和dfsq代码有两个问题:

  • 只复制第一个子节点 - 使用$ childNodes的临时副本解决
  • 孩子们将获得xmlns标签 - 通过在开头替换节点来解决 - 因此它连接到文档

更正的重命名功能是:

function renameTag( DOMElement $oldTag, $newTagName ) {
    $document = $oldTag->ownerDocument;

    $newTag = $document->createElement($newTagName);
    $oldTag->parentNode->replaceChild($newTag, $oldTag);

    foreach ($oldTag->attributes as $attribute) {
        $newTag->setAttribute($attribute->name, $attribute->value);
    }
    foreach (iterator_to_array($oldTag->childNodes) as $child) {
        $newTag->appendChild($oldTag->removeChild($child));
    }
    return $newTag;
}
Run Code Online (Sandbox Code Playgroud)


dfs*_*fsq 6

下一个功能将起到作用:

/**
 * @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>';
Run Code Online (Sandbox Code Playgroud)