как объединить xml файлы с атрибутами root? - PullRequest
1 голос
/ 12 июля 2020

У меня есть несколько файлов xml, и все они имеют атрибуты в root.

Примерно так:

FILE1. XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<item_root id="item01" name="Item 01">
    <child>content 01</child>
</item_root>

FILE2. XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<item_root id="item02" name="Item 02">
    <child>content 02</child>
</item_root>

... и т. Д.

Мне нужно объединить все файлы в один, динамически с php. Но в результате того, что я делаю, я не могу получить атрибуты root. Результат выглядит примерно так:

<?xml version="1.0"?>
<itens>
  <item_root>
    <child>content 01</child>
  </item_root>
  <item_root>
    <child>content 02</child>
  </item_root>
</itens>

Но он должен выглядеть так:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<itens>
  <item_root id="item01" name="Item 01">
    <child>content 01</child>
  </item_root>
  <item_root id="item02" name="Item 02">
    <child>content 02</child>
  </item_root>
</itens>

Мой код слияния выглядит так:

<?php
    $files= array(
      'xmlitens/file1.xml',
      'xmlitens/file2.xml'
    );
    
    $dom = new DOMDocument();
    $itens = $dom->createElement('itens');
    
    foreach ($files as $filename) {
      $fileaddDom = new DOMDocument();
      $fileaddDom->load($filename);
        $itemroot = $dom->createElement('item_root');
      if ($fileaddDom->documentElement) {
        foreach ($fileaddDom->documentElement->childNodes as $node) {
          $itemroot->appendChild(
            $dom->importNode($node, TRUE)
          );
        }
      }
      $itens->appendChild($itemroot);
    }
    $dom->appendChild($itens);
?>

Есть ли простой способ сделать это?

1 Ответ

0 голосов
/ 12 июля 2020

После того, как я разместил вопрос, ответ чудесным образом явился мне.

Вот решение, которое я нашел:

$files= array(
  'xmlitens/file1.xml',
  'xmlitens/file2.xml'
);

$dom = new DOMDocument();
$itens = $dom->createElement('itens');

foreach ($files as $filename) {
  $fileaddDom = new DOMDocument();
  $fileaddDom->load($filename);

  //This is the line that solves everything.
  $node = $fileaddDom->getElementsByTagName("item_root")->item(0);

  if ($fileaddDom->documentElement) {
     $itens->appendChild( $dom->importNode($node, true) );
  }
}
$dom->appendChild($itens);

Header('Content-type: text/xml');
print_r($dom->saveXML());
...