How to create XML in PHP

Code Snippet: Create XML in PHP

This article explores how to create XML in PHP. Here’s a solution using SimpleXMLElement class.

$products = [
    ["Name" => "Tomato Ketchup", "Price" => 2, "Availability" => 40],
    ["Name" => "Men Fragrance", "Price" => 160, "Availability" => 12],
    ["Name" => "Air Freshner", "Price" => 8, "Availability" => 50],
    ["Name" => "Cookies", "Price" => 1.5, "Availability" => 80],
];
 
$root = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><products/>');
 
foreach($products as $index => $subarray)
{
    $product = $root->addChild('product'); //<product></product>
    $product->addAttribute('Id', $index);  //Adds an ID attribute to the element product.
    foreach($subarray as $k => $v ) {
        $product->addChild($k, $v);        //Adds name, price and availability.
    }
}
 
$root->asXML('products.xml');

That’s one obvious option, but that’s not the only one. We will see another class that represents DOM documents in PHP. So, stay tuned to learn something exciting today.

Relevant Content: SimpleXMLElement in PHP

The SimpleXMLElement class represents an XML element and defines the methods necessary to create XML in PHP. We have often used this class in XML-related articles, but here we will focus entirely on building an XML tree from scratch in PHP. 

The two most frequently used methods for building an XML tree are

  • addChild – Creates a child element 
  • addAttribute – Creates an element’s attribute. 

This article explains how to create XML file with PHP. We will use a tree model illustration to visualize the XML better as we build it dynamically.

Scenario: Products Data in PHP Array

Background and Setup: PHP Array

We need a data source to populate XML elements. Therefore, we will use an array with a few everyday product data. This article is about generating XML tree so we won’t overcomplicate things and keep the source and data as simple as possible.

So, here’s the array of products available in memory. 

$products = [
    ["Name" => "Tomato Ketchup", "Price" => 2, "Availability" => 40],
    ["Name" => "Men Fragrance", "Price" => 160, "Availability" => 12],
    ["Name" => "Air Freshner", "Price" => 8, "Availability" => 50],
];

Option1: Create XML in PHP with SimpleXMLElement

First things first, we need to start with a root element. The root element houses the rest of the tree. We need to initialize the SimpleXMLElement object representing the root element, as follows.

$root = new SimpleXMLElement('&lt;?xml version="1.0" encoding="UTF-8"?>&lt;products/>
');

We have the root element. Here’s the initial tree model with root element only.

create XML in PHP

The tree will expand as we add children. But how to add data in XML file using PHP? The answer is the products array. So, let’s loop through the array and fetch the data. The succeeding elements will make use of the data.

foreach($products as $index => $subarray)
{
    $product = $root->addChild('product'); //<product></product>
    $product->addAttribute('Id', $index);  //Adds an ID attribute to the element product.
    foreach($subarray as $k => $v ) {
        $product->addChild($k, $v);        //Adds name, price and availability.
    }
}

This example is by no means a comprehensive algorithm for transforming an array to XML. To learn more about it, read array to XML in PHP. After the first iteration, the XML tree becomes.

XML tree

After all the iterations, we create an XML file PHP with asXML method.

$root->asXML('products.xml');

Here’s the output in an XML file.

&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;products>
    &lt;product Id="0">
        &lt;Name>Tomato Ketchup</Name>
        &lt;Price>2</Price>
        &lt;Availability>40</Availability>
    </product>
    &lt;product Id="1">
        &lt;Name>Men Fragrance</Name>
        &lt;Price>160</Price>
        &lt;Availability>12</Availability>
    </product>
    &lt;product Id="2">
        &lt;Name>Air Freshner</Name>
        &lt;Price>8</Price>
        &lt;Availability>50</Availability>
    </product>
</products>

The tree model finally looks like.

create XML in PHP

Here’s the full code.

$products = [
    ["Name" => "Tomato Ketchup", "Price" => 2, "Availability" => 40],
    ["Name" => "Men Fragrance", "Price" => 160, "Availability" => 12],
    ["Name" => "Air Freshner", "Price" => 8, "Availability" => 50],
    ["Name" => "Cookies", "Price" => 1.5, "Availability" => 80],
];
 
$root = new SimpleXMLElement('&lt;?xml version="1.0" encoding="UTF-8"?>&lt;products/>');
 
foreach($products as $index => $subarray)
{
    $product = $root->addChild('product'); //<product></product>
    $product->addAttribute('Id', $index);  //Adds an ID attribute to the element product.
    foreach($subarray as $k => $v ) {
        $product->addChild($k, $v);        //Adds name, price and availability.
    }
}
 
$root->asXML('products.xml');

SimpleXMLElement is the most useful class for XML related operations in PHP. But that’s not the only way. Let’s move on to the alternative option of how to generate XML file dynamically using PHP.

Option2: Create XML in PHP with DOMDocument

DOM stands for Document Object Model and it is a standard interface for representing an XML or HTML document or any tree-like model document. SimpleElementXML is based on the same idea but PHP gives a more explicit class DOMDocument for HTML and XML documents.

There are methods for adding children and attributes to an element as follows.

  • appendChild
  • createAttribute

The flow of the program remains the same as in the previous example. Here’s how to create XML file using PHP.

$products = [
    ["Name" => "Tomato Ketchup", "Price" => 2, "Availability" => 40],
    ["Name" => "Men Fragrance", "Price" => 160, "Availability" => 12],
    ["Name" => "Air Freshner", "Price" => 8, "Availability" => 50],
    ["Name" => "Cookies", "Price" => 1.5, "Availability" => 80],
];
 
$dom = new DOMDocument('1.0', 'utf-8');
 
$root = $dom->appendChild($dom->createElement('products'));
 
foreach($products as $index => $subarray)
{
    $product = $root->appendChild($dom->createElement('product')); //<product></product>
    $product_attribute = $dom->createAttribute('Id');
    $product_attribute->value = $index;
    $product->appendChild($product_attribute);  //Adds an ID attribute to the element product.
    foreach($subarray as $k => $v ) {
        $product->appendChild($dom->createElement($k, $v));        //Adds name, price and availability.
    }
}
 
$dom->save('products.xml');
 
?>

Here we go! It returns the same output as before. So that’s all about it, let’s jump to conclusion.

Conclusion

Wrap Up

This article demonstrates how to create XML in PHP. We have seen two options and two classes – SimpleXMLElement and DOMDocument for dynamically creating XML file with PHP. The article also includes visual representation of the XML tree as the program builds it up.

Classes and Functions Mentioned

SimpleXMLElement – (PHP 5, 7, 8) This is a core PHP class that helps in representing XML elements in PHP. It includes all the relevant methods necessary to work with XML. It has been included from PHP 5 all the way to PHP 8 and given its utility, it seems this class is here to stay in the future.

DOMDocument – (PHP 5, 7, 80 This is a core PHP class that represents HTML and XML in terms document object model (DOM). This concept is coherent with the tree model that we have seen because DOM treats XML and HTML as tree-based structures. The class seems to be stable and depreciation seems unlikely in the future.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

  Was this information helpful?

Can Your Career Use a Boost?

Check out our free PHP developer career guide. We created this guide as a resource to help fellow programmers level up their careers. This is an excellent resource whether you are new to programming or have been a professional for more than 15 years.

Click here to read the guide


Article Categories

Article Tags

© 2022 Confident.Systems