在php

时间:2016-12-19 09:35:41

标签: php xml dom simplexml

我有这样的XML:

<Categories>
  <Category Code="3014" Name="category-a" MasterCode="3015" />
  <Category Code="3015" Name="category-b" MasterCode="3010" />
  <Category Code="3010" Name="category-c" MasterCode="0" />
</Categories>

我想将此XML更改为:

<Categories>
  <Category1>category-a</Category1>
  <Category2>category-b</Category2>
  <Category3>category-c</Category3>
</Categories>

我尝试了许多示例代码解决方案但没有成功。

更新。我用这段代码解决了这个问题

    foreach ($item->getElementsByTagName('Categories') AS $item2) {
    $tip = 0;
    foreach ($item2->getElementsByTagName('Category') AS $item3) {
        $tip += 1;
        $item2->appendChild($xmlDoc->createElement('Category' . $tip, $item3->getAttribute('Name')));
        $delete[] = $item3;   
    }
}

1 个答案:

答案 0 :(得分:-1)

这是你的xml文件:

<?xml version="1.0" encoding="UTF-8"?> 
<root>
       <Categories>
        <Category Code="3014" Name="category-a" MasterCode="3015" />
        <Category Code="3015" Name="category-b" MasterCode="3010" />
        <Category Code="3010" Name="category-c" MasterCode="0" />
       </Categories>  
</root>

这是你的php文件:

$xmlDoc = new DOMDocument();
$xmlDoc->load('safa.xml');
$delete = array();
$tip = 1;
foreach ($xmlDoc->getElementsByTagName('Categories') AS $key => $item2) {
    foreach ($xmlDoc->getElementsByTagName('Category') AS $key => $item) {
        $item2->appendChild($xmlDoc->createElement('Category' . $tip, $item->getAttribute('Name')));
        $delete[] = $item;
        $tip += 1;
    }
}
foreach ($delete as $del) {
    $del->parentNode->removeChild($del);
}
$XMLData = $xmlDoc->saveXML();
fopen('safa_dump.xml', 'w');
file_put_contents('safa_dump.xml', $XMLData);

这是您的dump xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <Categories>
        <Category1>category-a</Category1>
        <Category2>category-b</Category2>
        <Category3>category-c</Category3>
    </Categories> 
</root>