mmusaib/xml-builder

A lightweight, fluent XML builder utility for PHP using native DOMDocument

Maintainers

Package info

github.com/mmusaib/xml-builder

pkg:composer/mmusaib/xml-builder

Statistics

Installs: 15

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v1.0.1 2026-01-07 17:24 UTC

This package is auto-updated.

Last update: 2026-03-19 06:51:30 UTC


README

A lightweight, fluent XML builder built on top of PHP's DOMDocument.

Installation

composer require mmusaib/xml-builder

Usage

use mmusaib\XmlBuilder\XmlBuilder;

$xml = new XmlBuilder('products');

$product = $xml->addElementToRoot('product');
$xml->addAttributes($product, [
    'id' => 101,
    'type' => 'digital'
]);

$xml->addElement($product, 'name', 'Premium Course');
$xml->addCDATAElement(
    $product,
    'description',
    '<strong>High quality content</strong>'
);

echo $xml->getXml();

🚀 Streaming Large XML Files (Chunk-Safe Mode)

When generating very large XML files (hundreds of thousands or millions of nodes), keeping everything in memory using DOMDocument can cause memory exhaustion. XmlBuilder supports streaming mode, allowing you to:

  • Keep the root element constant
  • Append children chunk by chunk
  • Write directly to a file
  • Keep memory usage extremely low

Start Streaming

$xml = new XmlBuilder('products');
$xml->startStream('products.xml');

This writes:

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

Append Nodes Per Chunk

foreach ($chunks as $chunk) {
    foreach ($chunk as $item) {
        $product = $xml->addElementToRoot('product');

        $xml->addElement($product, 'name', $item['name']);
        $xml->addElement($product, 'price', $item['price']);

        $xml->appendToStream($product);   // Writes & frees memory
    }
}

Each call:

  • Writes ... to file
  • Removes it from memory immediately

Finish Streaming

$xml->endStream();

This closes the root element:

</products>

✅ Why Use Streaming Mode?

Problem Streaming Solves
Millions of records ✔
Memory exhaustion ✔
Chunked DB processing ✔
Long-running jobs ✔

Features

  • Fluent XML creation
  • CDATA support
  • Attribute helpers
  • Encoding-safe
  • Pretty or compact output
  • PSR-4 autoloading

License

MIT