Web20 University

Convert an Array to XML in PHP (with examples)

Get Up to 65% Off PHP Hosting and Free Domains!

TL;DR

There’s a couple of classes PHP provides to help you convert between arrays an XML. The SimpleXMLElement is probably the most straightforward but if you’re trying to do something a bit more complicated then there are some other ways to get greater control of the XML you generate.

This article will give you some examples of converting both one-dimensional and associative arrays to XML using PHP.

How to Convert an Array to XML in PHP

PHP offers several methods to convert arrays to XML. Let’s explore two common approaches:

1. Using SimpleXMLElement

The SimpleXMLElement class provides a straightforward way to create XML from arrays:

function array_to_xml($array, $root_element = 'root') {
    $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><$root_element></$root_element>");
    
    function array_to_xml_recursive($array, &$xml) {
        foreach($array as $key => $value) {
            if(is_array($value)) {
                if(!is_numeric($key)){
                    $subnode = $xml->addChild("$key");
                    array_to_xml_recursive($value, $subnode);
                } else {
                    array_to_xml_recursive($value, $xml);
                }
            } else {
                $xml->addChild("$key", htmlspecialchars("$value"));
            }
        }
    }
    
    array_to_xml_recursive($array, $xml);
    return $xml->asXML();
}

2. Using DOMDocument

For more complex XML structures, the DOMDocument class offers greater flexibility:

function array_to_xml($array, $root_element = 'root') {
    $xml = new DOMDocument('1.0', 'UTF-8');
    $xml->formatOutput = true;
    $root = $xml->createElement($root_element);
    $xml->appendChild($root);
    
    function array_to_xml_recursive($array, &$xml, &$parent_node) {
        foreach($array as $key => $value) {
            if(is_array($value)) {
                if(!is_numeric($key)){
                    $subnode = $xml->createElement($key);
                    $parent_node->appendChild($subnode);
                    array_to_xml_recursive($value, $xml, $subnode);
                } else {
                    array_to_xml_recursive($value, $xml, $parent_node);
                }
            } else {
                $element = $xml->createElement($key, htmlspecialchars($value));
                $parent_node->appendChild($element);
            }
        }
    }
    
    array_to_xml_recursive($array, $xml, $root);
    return $xml->saveXML();
}

Considerations for Accurate Array to XML Conversion

When converting arrays to XML, keep these points in mind:

  1. Key Names: Ensure array keys are valid XML element names. They should start with a letter or underscore and contain only letters, numbers, hyphens, underscores, and periods.

  2. Special Characters: Use htmlspecialchars() to encode special characters in values to prevent XML parsing errors.

  3. Numeric Keys: Decide how to handle numeric array keys. You might want to use a generic element name or ignore the key entirely.

  4. Nested Arrays: Implement recursive functions to handle multi-dimensional arrays correctly.

  5. XML Declaration: Include the XML declaration at the beginning of your document.

  6. Namespace Handling: If working with namespaces, ensure your conversion function can handle them properly.

Tools for Array to XML Conversion

Several PHP libraries can assist with array to XML conversion:

  1. XMLWriter: A built-in PHP extension for creating XML documents.
  2. Spatie Array to XML: A popular package available via Composer.
  3. Array2XML: Another Composer package with a simple API.

Examples

Let’s look at some examples of converting arrays to XML:

One-Dimensional Array

$fruits = ['apple', 'banana', 'cherry'];
$xml = array_to_xml($fruits, 'fruits');
echo $xml;

Output:

<?xml version="1.0"?>
<fruits>
  <0>apple</0>
  <1>banana</1>
  <2>cherry</2>
</fruits>

Associative Array

$person = [
    'name' => 'John Doe',
    'age' => 30,
    'city' => 'New York'
];
$xml = array_to_xml($person, 'person');
echo $xml;

Output:

<?xml version="1.0"?>
<person>
  <name>John Doe</name>
  <age>30</age>
  <city>New York</city>
</person>

Multi-Dimensional Array

$employees = [
    'employee' => [
        [
            'name' => 'John Doe',
            'position' => 'Developer'
        ],
        [
            'name' => 'Jane Smith',
            'position' => 'Designer'
        ]
    ]
];
$xml = array_to_xml($employees, 'company');
echo $xml;

Output:

<?xml version="1.0"?>
<company>
  <employee>
    <name>John Doe</name>
    <position>Developer</position>
  </employee>
  <employee>
    <name>Jane Smith</name>
    <position>Designer</position>
  </employee>
</company>

Conclusion

Converting arrays to XML in PHP is a common task that can be accomplished using built-in classes like SimpleXMLElement and DOMDocument, or third-party libraries. By considering key factors like special character handling and nested array structures, you can ensure accurate and efficient conversions. The examples provided should give you a solid starting point for implementing array to XML conversion in your PHP projects.

Get Up to 65% Off PHP Hosting and Free Domains!