PHP XMLMaker: A Beginner’s Guide to Generating XML Files

10 Practical Examples Using PHP XMLMaker for Data ExportExporting data to XML is a common need in web development, integrations, and data interchange. PHP XMLMaker (a hypothetical or real library/tool—conceptually similar to helpers like SimpleXML or XMLWriter) helps you generate structured, well-formed XML quickly and reliably. This article provides 10 practical examples that show common data-export scenarios, patterns, and tips to produce maintainable XML output for integrations, APIs, feeds, and backups.


Table of contents

  1. Basic XML document generation
  2. Exporting an associative array to XML
  3. Exporting nested arrays (hierarchical data / categories)
  4. Exporting database result sets (MySQL)
  5. Streaming large datasets to XML (memory-efficient)
  6. Generating XML with attributes and namespaces
  7. Exporting CSV to XML using XMLMaker
  8. Creating an RSS feed from site posts
  9. Creating SOAP-like request XML for third-party APIs
  10. Validating and formatting XML output (pretty-print & encoding)

1 — Basic XML document generation

This first example shows how to initialize XMLMaker, set the root element, add a few child nodes, and output the XML as a string or file.

Example (conceptual):

<?php require 'vendor/autoload.php'; // if using composer $xml = new XMLMaker('utf-8');           // initialize with encoding $xml->startDocument('1.0', 'utf-8');   // optional $xml->setRoot('products'); $xml->addChild('product', [     'id' => 1,     'name' => 'Blue T-Shirt',     'price' => '19.99' ]); $xmlString = $xml->toString(); file_put_contents('products.xml', $xmlString); 

Notes:

  • Use proper escaping for content.
  • Choose UTF-8 to maximize compatibility.

2 — Exporting an associative array to XML

When you have configuration data or API responses as an associative array, converting it directly simplifies export workflows.

Pattern:

  • Walk the array recursively.
  • Convert scalar values to text nodes; arrays become nested elements.

Example:

<?php $data = [   'site' => [     'name' => 'My Store',     'url'  => 'https://example.com',     'settings' => [       'currency' => 'USD',       'timezone' => 'UTC'     ]   ] ]; $xml = new XMLMaker(); $xml->setRoot('export'); $xml->fromArray($data);   // hypothetical helper that handles recursion file_put_contents('export.xml', $xml->toString()); 

Tip: normalize keys (no spaces/special characters) before conversion.


3 — Exporting nested arrays (hierarchical data / categories)

For category trees, menus, or other nested structures, preserve parent-child relationships by nesting elements and including IDs or slugs.

Example:

<?php function addCategoryNode($xml, $nodeName, $category) {     $node = $xml->addChild($nodeName, ['id' => $category['id'], 'slug' => $category['slug']]);     $node->addChild('title', $category['title']);     if (!empty($category['children'])) {         foreach ($category['children'] as $child) {             addCategoryNode($xml, 'category', $child);         }     } } $xml = new XMLMaker(); $xml->setRoot('categories'); foreach ($categories as $cat) {     addCategoryNode($xml, 'category', $cat); } 

Include both id and parent_id where consumers need to rebuild trees without nesting.


4 — Exporting database result sets (MySQL)

Exporting SQL query results to XML is common for data migrations, reporting, and feeds.

Example:

<?php $pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass'); $stmt = $pdo->query('SELECT id, name, email, created_at FROM users'); $xml = new XMLMaker(); $xml->setRoot('users'); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {     $user = $xml->addChild('user', ['id' => $row['id']]);     $user->addChild('name', $row['name']);     $user->addChild('email', $row['email']);     $user->addChild('created_at', $row['created_at']); } file_put_contents('users.xml', $xml->toString()); 

Consider converting dates to ISO 8601 and excluding sensitive fields.


5 — Streaming large datasets to XML (memory-efficient)

For large exports, build XML incrementally and stream to the client or a file instead of storing the whole document in memory.

Pattern:

  • Use XMLWriter or XMLMaker’s streaming API.
  • Flush chunks periodically.

Example:

<?php $writer = new XMLWriter(); $writer->openURI('php://output'); // or a file path $writer->startDocument('1.0', 'UTF-8'); $writer->startElement('orders'); $sth = $pdo->query('SELECT * FROM orders'); while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {     $writer->startElement('order');     foreach ($row as $k => $v) {         $writer->writeElement($k, $v);     }     $writer->endElement(); // order     // flush happens automatically for php://output; for files, ensure buffers are manageable } $writer->endElement(); // orders $writer->endDocument(); 

Serve with appropriate headers for downloads and avoid timeouts with set_time_limit().


6 — Generating XML with attributes and namespaces

Many XML consumers expect attributes and namespaces (e.g., SOAP, RSS, Atom). Use XMLMaker features to add attributes and register namespaces.

Example:

<?php $xml = new XMLMaker(); $xml->setRoot('feed', ['xmlns' => 'http://www.w3.org/2005/Atom']); $entry = $xml->addChild('entry'); $entry->addChild('title', 'Post title'); $entry->addChild('link', null, ['href' => 'https://example.com/post/1']); // attribute on element 

Be explicit about namespace prefixes if the consumer requires them.


7 — Exporting CSV to XML using XMLMaker

Convert CSV rows into XML elements—useful for migrating spreadsheets or exports from legacy systems.

Example:

<?php if (($handle = fopen('data.csv', 'r')) !== false) {     $headers = fgetcsv($handle);     $xml = new XMLMaker();     $xml->setRoot('items');     while (($row = fgetcsv($handle)) !== false) {         $item = $xml->addChild('item');         foreach ($headers as $i => $header) {             $item->addChild($header, $row[$i]);         }     }     fclose($handle);     file_put_contents('data.xml', $xml->toString()); } 

Sanitize headers into valid tag names (lowercase, underscores).


8 — Creating an RSS feed from site posts

Generating RSS requires specific element names and date formats. Example creates a minimal RSS 2.0 feed.

Example:

<?php $xml = new XMLMaker(); $xml->setRoot('rss', ['version' => '2.0']); $channel = $xml->addChild('channel'); $channel->addChild('title', 'My Blog'); $channel->addChild('link', 'https://example.com'); $channel->addChild('description', 'Latest posts'); foreach ($posts as $post) {     $item = $channel->addChild('item');     $item->addChild('title', $post['title']);     $item->addChild('link', $post['url']);     $item->addChild('description', $post['summary']);     $item->addChild('pubDate', date(DATE_RSS, strtotime($post['published_at'])));     $item->addChild('guid', $post['url'], ['isPermaLink' => 'true']); } header('Content-Type: application/rss+xml; charset=utf-8'); echo $xml->toString(); 

Test in feed readers and validate with online RSS validators.


9 — Creating SOAP-like request XML for third-party APIs

When integrating with legacy SOAP or XML-based APIs, build precise request XML, respecting required namespaces and envelope structure.

Example:

<?php $xml = new XMLMaker(); $xml->setRoot('soapenv:Envelope', ['xmlns:soapenv' => 'http://schemas.xmlsoap.org/soap/envelope/', 'xmlns:ns' => 'http://example.com/api']); $body = $xml->addChild('soapenv:Body'); $req = $body->addChild('ns:DoAction'); $req->addChild('ns:Param1', 'value1'); $req->addChild('ns:Param2', 'value2'); $requestXml = $xml->toString(); $response = sendHttpPost('https://api.example.com/soap', $requestXml, ['Content-Type: text/xml']); 

Include proper SOAPAction headers if required.


10 — Validating and formatting XML output (pretty-print & encoding)

Validation ensures consumers can parse XML. Use libxml or DOMDocument to validate and format output.

Example:

<?php $dom = new DOMDocument('1.0', 'UTF-8'); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadXML($xmlString); if ($dom->schemaValidate('schema.xsd')) {     echo $dom->saveXML(); } else {     // handle validation errors } 

Always output UTF-8 and consider adding an XML declaration.


Horizontal line

Further tips

  • Escape special characters and CDATA for untrusted text.
  • Prefer ISO 8601 dates for interoperability.
  • Provide schema (XSD) or sample XML to consumers so they can validate.
  • For APIs, support both JSON and XML if possible to widen compatibility.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *