Skip to content
Advertisement

XML file/data handling with PHP

I have a XML file as a master file (master.xml) and its content is blank.

<?xml version="1.0" encoding="UTF-8"?>
<master/>

I have a loop in which i get some data and turn them into xml files (item.xml) and their content is like

<?xml version="1.0" encoding="UTF-8"?>
<master>
   <item>
      <key1>value1</key1>
      <key2>value2</key2>
      <key3>value3</key3>
   </item>
</master>

All i want, is to be able to get the Item from the item.xml and insert it on master.xml under the master tag so the final result would look something like

<?xml version="1.0" encoding="UTF-8"?>
<master>
  <item>
    <key1>value1</key1>
    <key2>value2</key2>
    <key3>value3</key3>
  </item>
  <item>
    <key1>value1</key1>
    <key2>value2</key2>
    <key3>value3</key3>
  </item>
  <item>
    <key1>value1</key1>
    <key2>value2</key2>
    <key3>value3</key3>
  </item>
  <item>
    <key1>value1</key1>
    <key2>value2</key2>
    <key3>value3</key3>
  </item>
</master>

I don’t know if it helps but the code right now is like this.

$targetDom = new DOMDocument();
$targetDom->load('master.xml');

while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
  // Data beeing processed and stored as item.xml

  $sourceDom = new DOMDocument();
  $sourceDom->load('item.xml');

  foreach ($sourceDom->documentElement->childNodes as $child) {
    $targetDom->appendChild(
      $targetDom->importNode($child, TRUE)
    );
  }
}

The code above has a result of this

<?xml version="1.0" encoding="UTF-8"?>
<master/>
<item>
  <key1>value1</key1>
  <key2>value2</key2>
  <key3>value3</key3>
</item>
<item>
  <key1>value1</key1>
  <key2>value2</key2>
  <key3>value3</key3>
</item>
<item>
  <key1>value1</key1>
  <key2>value2</key2>
  <key3>value3</key3>
</item>
<item>
  <key1>value1</key1>
  <key2>value2</key2>
  <key3>value3</key3>
</item>

What am i missing?

Advertisement

Answer

You need to append the items to the first element of the $targetDom

Use:

$targetDom->documentElement->appendChild(
  $targetDom->importNode($child, TRUE)
);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement