2011-11-17 118 views
8

我有一個看起來像這樣的XML文件:如何使用PHP更改XML標記名稱?

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

有一個簡單的方法來改變標籤名稱,到別的東西,如型號,價格。從本質上講,我有一堆XML文件包含類似的數據,但以不同的格式,所以我正在尋找一種簡單的方法來解析XML文件,更改某些標記名稱,並編寫一個新的XML文件改變了標籤名稱。

+0

是您的XML故意畸形? – kapa

+0

這些文件由多個來源提供 - 標籤名稱不受我控制。 –

+0

因此像' Data'(不同的結尾/結束標記)這樣的錯誤是否正常?因爲那樣你就不能真正用XML解析器解析這個文檔(比如PHP DOM)。 – kapa

回答

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>'; 
+0

我到底在哪裏加載原始XML文件? –

+0

查看我更新的答案。 – dfsq

+0

This Works!你會如何將$ xml寫入新文件? –

1

有一些示例代碼在我的問題over here中工作,但沒有通過DOMDocument/DOMElement更改標記名稱的直接方法,但可以使用新標記名複製元素,如圖所示。

基本上你必須:

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

    $newTag = $document->createElement($newTagName); 
    foreach($oldTag->attributes as $attribute) 
    { 
     $newTag->setAttribute($attribute->name, $attribute->value); 
    } 
    foreach($oldTag->childNodes as $child) 
    { 
     $newTag->appendChild($oldTag->removeChild($child)); 
    } 
    $oldTag->parentNode->replaceChild($newTag, $oldTag); 
    return $newTag; 
} 
+0

PHP在哪裏讀取XML文件? –

+0

@RPM:http://nl.php.net/manual/en/domdocument.loadxml.php – Kris

8

沒有與克里斯和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; 
}