PHPackages                             spatie/array-to-xml - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. spatie/array-to-xml

ActiveLibrary[API Development](/categories/api)

spatie/array-to-xml
===================

Convert an array to xml

3.4.4(5mo ago)1.2k57.8M—2.8%21420MITPHPPHP ^8.0CI passing

Since Mar 17Pushed 4w ago21 watchersCompare

[ Source](https://github.com/spatie/array-to-xml)[ Packagist](https://packagist.org/packages/spatie/array-to-xml)[ Docs](https://github.com/spatie/array-to-xml)[ Fund](https://spatie.be/open-source/support-us)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/spatie-array-to-xml/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (56)Used By (20)

Convert an array to xml
=======================

[](#convert-an-array-to-xml)

[![Latest Version](https://camo.githubusercontent.com/90d99372be6fc674e9deca47ddcf03f51f22f5dc5c4323ef8d51ddabe9325ddd/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f7370617469652f61727261792d746f2d786d6c2e7376673f7374796c653d666c61742d737175617265)](https://github.com/spatie/array-to-xml/releases)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Tests](https://github.com/spatie/array-to-xml/workflows/Tests/badge.svg)](https://github.com/spatie/array-to-xml/workflows/Tests/badge.svg)[![Total Downloads](https://camo.githubusercontent.com/4f3ea058d8eae1a18c4c592287cda0a1b80b702d183c8c5090b4f8da590a6a02/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f61727261792d746f2d786d6c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/array-to-xml)

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

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/6c453d6a3afb9722ae332a1be1f4e4bd7ee8eaf679cf663bc23f6fb6ebe0c488/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f61727261792d746f2d786d6c2e6a70673f743d31)](https://spatie.be/github-ad-click/array-to-xml)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

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](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Install
-------

[](#install)

You can install this package via composer.

```
composer require spatie/array-to-xml
```

Usage
-----

[](#usage)

```
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:

```

        Luke Skywalker
        Lightsaber

        Sauron
        Evil Eye

```

### Setting the name of the root element

[](#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

[](#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

[](#adding-attributes)

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

```
$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:

```

        Luke Skywalker
        Lightsaber

        Sauron
        Evil Eye

        Harry Potter

    300

```

*Note, that the value of the `_value` field must be a string. [(More)](https://github.com/spatie/array-to-xml/issues/75#issuecomment-413726065)*

### Adding comments

[](#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.

```
$array = [
    'Good guy' => [
        '_comment' => 'Our hero',
        'name' => 'Luke Skywalker',
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => 'Sauron',
        'weapon' => 'Evil Eye',
        '_comment' => 'Finally gone',
    ],
    'Another guy' => [
        '_comment' => 'The GOAT',
        'name' => 'John Wick',
        '_comment2' => 'famous for',
        'weapon' => 'Pencil',
        '_comment_other' => 'His dog needs an entry',
    ];
    'The survivor' => [
        '_attributes' => ['house'=>'Hogwarts'],
        '_value' => 'Harry Potter',
        '_comment' => 'He made it',
    ]
];

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

This code will result in:

```

        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

[](#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.

```
$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:

```

        Luke Skywalker]]>
        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

[](#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)

```
$result = ArrayToXml::convert($array, [], true, 'UTF-8', '1.1', [], true);
```

This will result in:

```

```

### Adding attributes to the root element

[](#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.

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

### Using a multi-dimensional array

[](#using-a-multi-dimensional-array)

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

```
$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:

```

            Luke Skywalker
            Lightsaber

            Captain America
            Shield

            Sauron
            Evil Eye

            Darth Vader
            Lightsaber

```

### Using Closure values

[](#using-closure-values)

The package can use Closure values:

```
$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:

```

        one
        10
        20

        two
        12
        24

```

### Handling numeric keys

[](#handling-numeric-keys)

The package can also can handle numeric keys:

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

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

This will result in:

```

        Vladimir
        greeflas

        Marina
        estacet

```

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

### Using custom keys

[](#using-custom-keys)

The package can also can handle custom keys:

```
$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:

```

        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:

```
$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:

```

        Vladimir
        greeflas

        Marina
        estacet

            first-tag
            second-tag

```

### Setting DOMDocument properties

[](#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 .

You can use the constructor to set DOMDocument properties.

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

Alternatively you can use `setDomProperties`

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

### XML Prettification

[](#xml-prettification)

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

Example:

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

With prettification:

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

will result in:

```

        Luke Skywalker
        Lightsaber

        Sauron
        Evil Eye

```

Without prettification:

```
$arrayToXml->toXml();
```

will result in:

```

Luke SkywalkerLightsaberSauronEvil Eye
```

### Dropping XML declaration

[](#dropping-xml-declaration)

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

Example:

```
$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:

```
soap:value
```

### Adding processing instructions

[](#adding-processing-instructions)

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

Example:

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

This will result in:

```

Luke SkywalkerLightsaberSauronEvil Eye
```

Testing
-------

[](#testing)

```
vendor/bin/phpunit
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Postcardware
------------

[](#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](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

77

—

ExcellentBetter than 100% of packages

Maintenance85

Actively maintained with recent releases

Popularity77

Solid adoption and visibility

Community52

Growing community involvement

Maturity82

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 60.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~72 days

Recently: every ~90 days

Total

55

Last Release

155d ago

Major Versions

0.0.1 → 1.0.02015-03-17

1.0.3 → 2.0.02015-10-08

2.16.0 → 3.0.02021-04-23

2.17.0 → 3.1.52022-12-24

v2.x-dev → 3.1.62023-05-11

PHP version history (9 changes)0.0.1PHP &gt;=5.3.0

2.2.1PHP ^5.4|^7.0

2.5.0PHP ^5.6|^7.0

2.5.2PHP ^7.0

2.8.1PHP ^7.1

2.11.0PHP ^7.2

2.15.1PHP ^7.4|^8.0

3.0.0PHP ^8.0

3.1.4PHP ^8.0 || ^8.1 || ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (125 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (16 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (11 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (9 commits)")[![dimitri-koenig](https://avatars.githubusercontent.com/u/4375825?v=4)](https://github.com/dimitri-koenig "dimitri-koenig (5 commits)")[![elyotechgit](https://avatars.githubusercontent.com/u/251508?v=4)](https://github.com/elyotechgit "elyotechgit (4 commits)")[![SuperDJ](https://avatars.githubusercontent.com/u/6484766?v=4)](https://github.com/SuperDJ "SuperDJ (3 commits)")[![radeno](https://avatars.githubusercontent.com/u/58521?v=4)](https://github.com/radeno "radeno (3 commits)")[![willemwollebrants](https://avatars.githubusercontent.com/u/916958?v=4)](https://github.com/willemwollebrants "willemwollebrants (2 commits)")[![akoepcke](https://avatars.githubusercontent.com/u/5311185?v=4)](https://github.com/akoepcke "akoepcke (2 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![andreybolonin](https://avatars.githubusercontent.com/u/2576509?v=4)](https://github.com/andreybolonin "andreybolonin (2 commits)")[![crynobone](https://avatars.githubusercontent.com/u/172966?v=4)](https://github.com/crynobone "crynobone (2 commits)")[![dmaksimov](https://avatars.githubusercontent.com/u/497369?v=4)](https://github.com/dmaksimov "dmaksimov (2 commits)")[![Gemorroj](https://avatars.githubusercontent.com/u/885731?v=4)](https://github.com/Gemorroj "Gemorroj (2 commits)")[![patinthehat](https://avatars.githubusercontent.com/u/5508707?v=4)](https://github.com/patinthehat "patinthehat (2 commits)")[![iLexN](https://avatars.githubusercontent.com/u/4638751?v=4)](https://github.com/iLexN "iLexN (1 commits)")[![nikolaybaychenko](https://avatars.githubusercontent.com/u/13581265?v=4)](https://github.com/nikolaybaychenko "nikolaybaychenko (1 commits)")[![olsza](https://avatars.githubusercontent.com/u/12556170?v=4)](https://github.com/olsza "olsza (1 commits)")[![byoan](https://avatars.githubusercontent.com/u/16349626?v=4)](https://github.com/byoan "byoan (1 commits)")

---

Tags

apiarrayconfigurationxmlxmlarrayconvert

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/spatie-array-to-xml/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-array-to-xml/health.svg)](https://phpackages.com/packages/spatie-array-to-xml)
```

###  Alternatives

[mtownsend/xml-to-array

Easily convert valid xml to a php array.

1163.5M21](/packages/mtownsend-xml-to-array)[lstrojny/fxmlrpc

Fast and tiny XML/RPC client with bridges for various HTTP clients

1425.4M30](/packages/lstrojny-fxmlrpc)[nathanmac/parser

Simple PHP Parser Utility Library for API Development

2151.0M3](/packages/nathanmac-parser)[mtownsend/response-xml

The missing XML support for Laravel's Response class.

1041.2M3](/packages/mtownsend-response-xml)[convertapi/convertapi-php

Convert API PHP Client

523.9M](/packages/convertapi-convertapi-php)[pdfcrowd/pdfcrowd

A client library for the Pdfcrowd API. It lets you convert between HTML, PDF and various image formats

631.1M1](/packages/pdfcrowd-pdfcrowd)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
