How to Convert an array to XML using PHP

Convert an array to XML string using php

0 333

If you want to render php array output into XML then here I am going to share a wonderful PHP class to easily convert multidimensional array to XML. You can also use same for creating API’s to share your data with other’s in XML format. As you know XML (Extensible Markup Language) is a markup language that encodes documents in a machine-readable and human-readable format. Generally, XML is used to store and transport data. XML can help you to free the space from the database. Instead of the database you can store the data in the XML file and retrieve data from XML file without connecting to the database and using php.

First Download ArrayToXml.php Class from official github repository.
You can also install this package via composer.

composer require spatie/array-to-xml

Include ArrayToXml.php on page then call the function.
Bellow is the sample example to convert array to XML.

“>

use Spatie\ArrayToXml\ArrayToXml;
$array = [
    'Good guy' => [
        'name' => 'Luke Skywalker',
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => 'Sauron',
        'weapon' => 'Evil Eye'
    ]
];
 
$result = ArrayToXml::convert($array);

After running this piece of code $result will contain:

<?xml version="1.0"?>
<root>
    <Good_guy>
        <name>Luke Skywalker</name>
        <weapon>Lightsaber</weapon>
    </Good_guy>
    <Bad_guy>
        <name>Sauron</name>
        <weapon>Evil Eye</weapon>
    </Bad_guy>
</root>

 

Optionally you can set the name of the rootElement by passing it as the second argument. If you don’t specify this argument (or set it to an empty string) “root” will be used.

$result = ArrayToXml::convert($array, 'customrootname');

By default all spaces in the key names of your array will be converted to underscores. If you want to opt out of this behaviour you can set the third argument to false. We’ll leave all keynames alone.

$result = ArrayToXml::convert($array, 'customrootname', false);

You can use a key named _attributes to add attributes to a node.

$array = [
    'Good guy' => [
        '_attributes' => ['attr1' => 'value'],
        'name' => 'Luke Skywalker',
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => 'Sauron',
        'weapon' => 'Evil Eye'
    ]
];
 
$result = ArrayToXml::convert($array);

OUTPUT:

<?xml version="1.0"?>
<root>
    <Good_guy attr1="value">
        <name>Luke Skywalker</name>
        <weapon>Lightsaber</weapon>
    </Good_guy>
    <Bad_guy>
        <name>Sauron</name>
        <weapon>Evil Eye</weapon>
    </Bad_guy>
</root>

Download ArrayToXml.php Class or read full documentation to use this feature in your project.

 

Leave A Reply

Your email address will not be published.