Skip to content

Instantly share code, notes, and snippets.

@tbreuss
Created December 7, 2024 05:44
Show Gist options
  • Save tbreuss/6702051b0b7ca1cb46379be395423b72 to your computer and use it in GitHub Desktop.
Save tbreuss/6702051b0b7ca1cb46379be395423b72 to your computer and use it in GitHub Desktop.
Splits a large XML file with many elements into individual XML files per element using PHP and DOMDocument
<?php
/**
* Splits a large XML file with many elements into individual XML files per element using PHP and DOMDocument
*
* The script does the following:
* - Load original XML
* - Create template XML and remove elements
* - For each element of the original XML
* - Create a clone of the template XML
* - Add element of the original XML to the clone
* - Update other nodes of the clone
* - Save clone
*/
// create source
$source = new DOMDocument;
$source->preserveWhiteSpace = false;
$source->load('xml-input.xml');
// create template without items
$template = $source->cloneNode(true);
foreach (iterator_to_array($template->getElementsByTagName('item')) as $item) {
$item->parentNode->removeChild($item);
}
// create separate xml for each item
foreach ($source->getElementsByTagName('item') as $index => $item) {
$chunk = $template->cloneNode(true);
$chunk->formatOutput = true;
$newItem = $chunk->importNode($item, true);
$chunk->getElementsByTagName('items')->item(0)->appendChild($newItem);
$chunk->getElementsByTagName('title')->item(0)->nodeValue = 'XML with one item';
$chunk->getElementsByTagName('counter')->item(0)->nodeValue = '1';
$chunk->save('xml-output-' . ($index + 1) . '.xml');
}
<?xml version="1.0" encoding="UTF-8"?>
<root>
<title>XML with three items</title>
<items>
<item>
<id>1</id>
<name>Item One</name>
</item>
<item>
<id>2</id>
<name>Item Two</name>
</item>
<item>
<id>3</id>
<name>Item Three</name>
</item>
</items>
<counter>3</counter>
</root>
<!-- xml-output-1.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<root>
<title>XML with one item</title>
<items>
<item>
<id>1</id>
<name>Item One</name>
</item>
</items>
<counter>1</counter>
</root>
<!-- xml-output-2.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<root>
<title>XML with one item</title>
<items>
<item>
<id>2</id>
<name>Item Two</name>
</item>
</items>
<counter>1</counter>
</root>
<!-- xml-output-3.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<root>
<title>XML with one item</title>
<items>
<item>
<id>3</id>
<name>Item Three</name>
</item>
</items>
<counter>1</counter>
</root>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment