Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

array-to-xml

> 编程语言
Open source

A simple class to convert an array to xml

1.2K stars0 likes3 views
WebsiteGitHub

About

A simple class to convert an array to xml

Convert an array to xml

This package provides a very simple class to convert an array to an xml string.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Install

You can install this package via composer.

bash
composer require spatie/array-to-xml

Usage

php
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

    
        Luke Skywalker
        Lightsaber
    
    
        Sauron
        Evil Eye
    

Setting the name of the root element

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');

Handling key names

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);

Adding attributes

You can use a key named _attributes to add attributes to a node, and _value to specify the value.

php
$array = [
    'Good guy' => [
        '_attributes' => ['attr1' => 'value'],
        'name' => 'Luke Skywalker',
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => 'Sauron',
        'weapon' => 'Evil Eye'
    ],
    'The survivor' => [
        '_attributes' => ['house'=>'Hogwarts'],
        '_value' => 'Harry Potter'
    ],
    'Good movie' => [
        '_attributes' => ['category' => 'Action'],
        '_value' => 300,
    ],
];

$result = ArrayToXml::convert($array);

This code will result in:

xml

    
        Luke Skywalker
        Lightsaber
    
    
        Sauron
        Evil Eye
    
    
        Harry Potter
    
    300

Note, that the value of the _value field must be a string. (More)

Adding comments

You can use a key named _comment to add a comment to a node. The exact placement depends on where you put the key in your array. You can also add multiple keys starting with _comment to add multiple comments.

…

This code will result in:

xml

    
        
        Luke Skywalker
        Lightsaber
    
    
        Sauron
        Evil Eye
        
    
    
        
        John Wick
        
        Pencil
        
    
    Harry Potter

[!NOTE] A comment will be omitted if the value is an empty string "" or null.

Using reserved characters

It is also possible to wrap the value of a node into a CDATA section. This allows you to use reserved characters.

php
$array = [
    'Good guy' => [
        'name' => [
            '_cdata' => '
Luke Skywalker
'
        ],
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => '
Sauron
',
        'weapon' => 'Evil Eye'
    ]
];

$result = ArrayToXml::convert($array);

This code will result in:

xml

    
        
        Lightsaber
    
    
        &lt;h1&gt;Sauron&lt;/h1&gt;
        Evil Eye
    

If your input contains something that cannot be parsed a DOMException will be thrown.

Customize the XML declaration

You could specify specific values in for:

  • encoding as the fourth argument (string)
  • version as the fifth argument (string)
  • DOM properties as the sixth argument (array)
  • standalone as seventh argument (boolean)
php
$result = ArrayToXml::convert($array, [], true, 'UTF-8', '1.1', [], true);

This will result in:

xml

Adding attributes to the root element

To add attributes to the root element provide an array with an _attributes key as the second argument. The root element name can then be set using the rootElementName key.

php
$result = ArrayToXml::convert($array, [
    'rootElementName' => 'helloyouluckypeople',
    '_attributes' => [
        'xmlns' => 'https://github.com/spatie/array-to-xml',
    ],
], true, 'UTF-8');

Using a multi-dimensional array

Use a multi-dimensional array to create a collection of elements.

php
$array = [
    'Good guys' => [
        'Guy' => [
            ['name' => 'Luke Skywalker', 'weapon' => 'Lightsaber'],
            ['name' => 'Captain America', 'weapon' => 'Shield'],
        ],
    ],
    'Bad guys' => [
        'Guy' => [
            ['name' => 'Sauron', 'weapon' => 'Evil Eye'],
            ['name' => 'Darth Vader', 'weapon' => 'Lightsaber'],
        ],
    ],
];

This will result in:

xml

    
        
            Luke Skywalker
            Lightsaber
        
        
            Captain America
            Shield
        
    
    
        
            Sauron
            Evil Eye
        
        
            Darth Vader
            Lightsaber
        
    

Using Closure values

The package can use Closure values:

php
$users = [
    [
        'name' => 'one',
        'age' => 10,
    ],
    [
        'name' => 'two',
        'age' => 12,
    ],
];

$array = [
    'users' => function () use ($users) {
        $new_users = [];
        foreach ($users as $user) {
            $new_users[] = array_merge(
                $user,
                [
                    'double_age' => $user['age'] * 2,
                ]
            );
        }

        return $new_users;
    },
];

ArrayToXml::convert($array)

This will result in:

xml

    
        one
        10
        20
    
    
        two
        12
        24
    

Handling numeric keys

The package can also can handle numeric keys:

php
$array = [
    100 => [
        'name' => 'Vladimir',
        'nickname' => 'greeflas',
    ],
    200 => [
        'name' => 'Marina',
        'nickname' => 'estacet',
    ],
];

$result = ArrayToXml::convert(['__numeric' => $array]);

This will result in:

xml

    
        Vladimir
        greeflas
    
    
        Marina
        estacet
    

You can change key prefix with setter method called setNumericTagNamePrefix().

Using custom keys

The package can also can handle custom keys:

php
$array = [
    '__custom:custom-key:1' => [
        'name' => 'Vladimir',
        'nickname' => 'greeflas',
    ],
    '__custom:custom-key:2' => [
        'name' => 'Marina',
        'nickname' => 'estacet',
        'tags' => [
            '__custom:tag:1' => 'first-tag',
            '__custom:tag:2' => 'second-tag',
        ]
    ],
];

$result = ArrayToXml::convert($array);

This will result in:

xml

    
        Vladimir
        greeflas
    
    
        Marina
        estacet
        
            first-tag
            second-tag
        
    

A custom key contains three, colon-separated parts: "__custom:[custom-tag]:[unique-string]".

  • "__custom"
    • The key always starts with "__custom".
  • [custom-tag]
    • The string to be rendered as the XML tag.
  • [unique-string]
    • A unique string that avoids overwriting of duplicate keys in PHP arrays.

a colon character can be included within the custom-tag portion by escaping it with a backslash:

php
$array = [
    '__custom:ns\\:custom-key:1' => [
        'name' => 'Vladimir',
        'nickname' => 'greeflas',
    ],
    '__custom:ns\\:custom-key:2' => [
        'name' => 'Marina',
        'nickname' => 'estacet',
        'tags' => [
            '__custom:ns\\:tag:1' => 'first-tag',
            '__custom:ns\\:tag:2' => 'second-tag',
        ]
    ],
];

This will result in:

xml

    
        Vladimir
        greeflas
    
    
        Marina
        estacet
        
            first-tag
            second-tag
        
    

Setting DOMDocument properties

To set properties of the internal DOMDocument object just pass an array consisting of keys and values. For a full list of valid properties consult https://www.php.net/manual/en/class.domdocument.php.

You can use the constructor to set DOMDocument properties.

php
$result = ArrayToXml::convert(
   $array, 
   $rootElement, 
   $replaceSpacesByUnderScoresInKeyNames, 
   $xmlEncoding, 
   $xmlVersion, 
   ['formatOutput' => true]
);

Alternatively you can use setDomProperties

php
$arrayToXml = new ArrayToXml($array);
$arrayToXml->setDomProperties(['formatOutput' => true]);
$result = $arrayToXml->toXml();

XML Prettification

Call $arrayToXml->prettify() method on ArrayToXml to set XML in pretty form.

Example:

php
$array = [
    'Good guy' => [
        'name' => 'Luke Skywalker',
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => 'Sauron',
        'weapon' => 'Evil Eye'
    ]
];
$arrayToXml = new ArrayToXml($array);

With prettification:

php
$arrayToXml->prettify()->toXml();

will result in:

xml

    
        Luke Skywalker
        Lightsaber
    
    
        Sauron
        Evil Eye
    

Without prettification:

php
$arrayToXml->toXml();

will result in:

xml

Luke SkywalkerLightsaberSauronEvil Eye

Dropping XML declaration

Call $arrayToXml->dropXmlDeclaration() method on ArrayToXml object to omit default XML declaration on top of the generated XML.

Example:

php
$root = [
    'rootElementName' => 'soap:Envelope',
    '_attributes' => [
        'xmlns:soap' => 'http://www.w3.org/2003/05/soap-envelope/',
    ],
];
$array = [
    'soap:Header' => [],
    'soap:Body' => [
        'soap:key' => 'soap:value',
    ],
];
$arrayToXml = new ArrayToXml($array, $root);

$result = $arrayToXml->dropXmlDeclaration()->toXml();

This will result in:

xml
soap:value

Adding processing instructions

Call $arrayToXml->addProcessingInstruction($target, $data) method on ArrayToXml object to prepend a processing instruction before the root element.

Example:

php
$arrayToXml = new ArrayToXml($array);
$arrayToXml->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="base.xsl"');
$result = $arrayToXml->toXml();

This will result in:

xml

Luke SkywalkerLightsaberSauronEvil Eye

Testing

bash
vendor/bin/phpunit

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

  • Freek Van der Herten
  • All Contributors

License

The MIT License (MIT). Please see License File for more information.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPapiarrayconfigurationxml

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言