PHPackages                             jackiedo/xml-array - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. jackiedo/xml-array

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

jackiedo/xml-array
==================

Simple tools to work with the conversion between xml and array

1.1.1(3y ago)879.5k↓25.7%1[2 issues](https://github.com/JackieDo/Xml-Array/issues)MITPHPPHP &gt;=5.4.0

Since Nov 24Pushed 3y ago1 watchersCompare

[ Source](https://github.com/JackieDo/Xml-Array)[ Packagist](https://packagist.org/packages/jackiedo/xml-array)[ RSS](/packages/jackiedo-xml-array/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (11)Used By (0)

Xml-Array
=========

[](#xml-array)

[![Run tests](https://github.com/JackieDo/Xml-Array/actions/workflows/run-tests.yml/badge.svg)](https://github.com/JackieDo/Xml-Array/actions/workflows/run-tests.yml)[![Total Downloads](https://camo.githubusercontent.com/50347c772f94fbdead0f5c4f362a562a707fb2ae926addcef152f393b39010b7/68747470733a2f2f706f7365722e707567782e6f72672f6a61636b6965646f2f786d6c2d61727261792f646f776e6c6f616473)](https://packagist.org/packages/jackiedo/xml-array)[![Latest Stable Version](https://camo.githubusercontent.com/491ea75f9e6275f77b7492c14c0c8f0355780d6f5fc68acd8854cd62df881fc8/68747470733a2f2f706f7365722e707567782e6f72672f6a61636b6965646f2f786d6c2d61727261792f762f737461626c65)](https://packagist.org/packages/jackiedo/xml-array)[![License](https://camo.githubusercontent.com/9d6c4c3e02b6d1692169020d3c38acf2d4c7613e1ce485ce677e519d617fa8f9/68747470733a2f2f706f7365722e707567782e6f72672f6a61636b6965646f2f786d6c2d61727261792f6c6963656e7365)](https://packagist.org/packages/jackiedo/xml-array)

The conversion between xml and array becomes easier than ever. This package provides some very simple classes to convert XML to array and back.

Features of this package
========================

[](#features-of-this-package)

- Convert an XML object (DOMDocument, SimpleXMLElement) or well-formed XML string to an associative array or Json string.
- Convert an associative array to well-formed XML string or DOMDocument.
- Support parsing and building attributes, Cdata sections and namespaces of XML in conversion process.

Overview
========

[](#overview)

Look at one of the following sessions to learn more about this package.

- [Xml-Array](#xml-array)
- [Features of this package](#features-of-this-package)
- [Overview](#overview)
    - [Installation](#installation)
    - [Basic usage](#basic-usage)
        - [Convert from XML](#convert-from-xml)
        - [Convert from array](#convert-from-array)
    - [Advanced usage](#advanced-usage)
        - [Set configuration](#set-configuration)
            - [Method 1](#method-1)
            - [Method 2](#method-2)
            - [Method 3](#method-3)
        - [Get configuration](#get-configuration)
        - [Default configuration](#default-configuration)
            - [For Xml2Array](#for-xml2array)
            - [For Array2Xml](#for-array2xml)
        - [Effect of configuration settings](#effect-of-configuration-settings)
            - [version](#version)
            - [encoding](#encoding)
            - [standalone](#standalone)
            - [attributesKey, cdataKey, valueKey](#attributeskey-cdatakey-valuekey)
            - [namespacesOnRoot](#namespacesonroot)
            - [rootElement](#rootelement)
            - [keyFixer](#keyfixer)
- [License](#license)

Installation
------------

[](#installation)

You can install this package through [Composer](https://getcomposer.org).

```
$ composer require jackiedo/xml-array
```

Basic usage
-----------

[](#basic-usage)

### Convert from XML

[](#convert-from-xml)

Web have two following methods:

**Convert to array**:

```
Xml2Array::convert(DOMDocument|SimpleXMLElement|string $inputXML)->toArray();
```

**Convert to Json**:

```
Xml2Array::convert(DOMDocument|SimpleXMLElement|string $inputXML)->toJson(int $flag = 0);
```

> **Note:** The input XML can be one of types DOMDocument object, SimpleXMLElement object or well-formed XML string.

**Example 1**: - *(Convert from XML string)*

```
use Jackiedo\XmlArray\Xml2Array;
...

$xmlString = '

        Example tag

        Another tag with attributes

            Sub tag 1
            Sub tag 2

            Hello

            Section number 1
            Section number 2
            Section number 3

            Content

    ';

$array = Xml2Array::convert($xmlString)->toArray();
```

After running this piece of code `$array` will contain:

```
$array = [
    "root_node" => [
        "tag"           => "Example tag",
        "attribute_tag" => [
            "@value"      => "Another tag with attributes",
            "@attributes" => [
                "description" => "This is a tag with attribute"
            ]
        ],
        "cdata_section" => [
            "@cdata" => "This is CDATA section"
        ],
        "tag_with_subtag" => [
            "sub_tag" => ["Sub tag 1", "Sub tag 2"]
        ],
        "mixed_section" => [
            "@value"  => "Hello",
            "@cdata"  => "This is another CDATA section",
            "section" => [
                [
                    "@value"      => "Section number 1",
                    "@attributes" => [
                        "id" => "sec_1"
                    ]
                ],
                [
                    "@value"      => "Section number 2",
                    "@attributes" => [
                        "id" => "sec_2"
                    ]
                ],
                [
                    "@value"      => "Section number 3",
                    "@attributes" => [
                        "id" => "sec_3"
                    ]
                ]
            ]
        ],
        "example:with_namespace" => [
            "example:sub" => "Content"
        ],
        "@attributes" => [
            "xmlns:example" => "http://example.com"
        ]
    ]
]
```

**Example 2**: - *(Convert form XML object, such as SimpleXMLElement)*

```
use Jackiedo\XmlArray\Xml2Array;
...

$xmlObject = simplexml_load_file('https://www.vietcombank.com.vn/ExchangeRates/ExrateXML.aspx');
$array     = Xml2Array::convert($xmlObject)->toArray();
```

The result of above code is:

```
$array = [
    "ExrateList" => [
        "DateTime" => "11/26/2018 1:56:20 PM",
        "Exrate" => [
            [
                "@attributes" => [
                    "CurrencyCode" => "AUD",
                    "CurrencyName" => "AUST.DOLLAR",
                    "Buy" => "16724.09",
                    "Transfer" => "16825.04",
                    "Sell" => "17008.7"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "CAD",
                    "CurrencyName" => "CANADIAN DOLLAR",
                    "Buy" => "17412.21",
                    "Transfer" => "17570.34",
                    "Sell" => "17762.14"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "CHF",
                    "CurrencyName" => "SWISS FRANCE",
                    "Buy" => "23074.67",
                    "Transfer" => "23237.33",
                    "Sell" => "23538.02"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "DKK",
                    "CurrencyName" => "DANISH KRONE",
                    "Buy" => "0",
                    "Transfer" => "3493.19",
                    "Sell" => "3602.67"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "EUR",
                    "CurrencyName" => "EURO",
                    "Buy" => "26264.39",
                    "Transfer" => "26343.42",
                    "Sell" => "26736.61"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "GBP",
                    "CurrencyName" => "BRITISH POUND",
                    "Buy" => "29562.43",
                    "Transfer" => "29770.83",
                    "Sell" => "30035.68"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "HKD",
                    "CurrencyName" => "HONGKONG DOLLAR",
                    "Buy" => "2939.91",
                    "Transfer" => "2960.63",
                    "Sell" => "3004.95"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "INR",
                    "CurrencyName" => "INDIAN RUPEE",
                    "Buy" => "0",
                    "Transfer" => "331.15",
                    "Sell" => "344.15"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "JPY",
                    "CurrencyName" => "JAPANESE YEN",
                    "Buy" => "200.38",
                    "Transfer" => "202.4",
                    "Sell" => "207.05"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "KRW",
                    "CurrencyName" => "SOUTH KOREAN WON",
                    "Buy" => "19.07",
                    "Transfer" => "20.07",
                    "Sell" => "21.33"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "KWD",
                    "CurrencyName" => "KUWAITI DINAR",
                    "Buy" => "0",
                    "Transfer" => "76615.44",
                    "Sell" => "79621.23"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "MYR",
                    "CurrencyName" => "MALAYSIAN RINGGIT",
                    "Buy" => "0",
                    "Transfer" => "5532.17",
                    "Sell" => "5603.76"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "NOK",
                    "CurrencyName" => "NORWEGIAN KRONER",
                    "Buy" => "0",
                    "Transfer" => "2674.72",
                    "Sell" => "2758.55"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "RUB",
                    "CurrencyName" => "RUSSIAN RUBLE",
                    "Buy" => "0",
                    "Transfer" => "349.9",
                    "Sell" => "389.89"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "SAR",
                    "CurrencyName" => "SAUDI RIAL",
                    "Buy" => "0",
                    "Transfer" => "6206.27",
                    "Sell" => "6449.75"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "SEK",
                    "CurrencyName" => "SWEDISH KRONA",
                    "Buy" => "0",
                    "Transfer" => "2536.35",
                    "Sell" => "2600.19"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "SGD",
                    "CurrencyName" => "SINGAPORE DOLLAR",
                    "Buy" => "16775.66",
                    "Transfer" => "16893.92",
                    "Sell" => "17078.33"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "THB",
                    "CurrencyName" => "THAI BAHT",
                    "Buy" => "691.64",
                    "Transfer" => "691.64",
                    "Sell" => "720.49"
                ]
            ],
            [
                "@attributes" => [
                    "CurrencyCode" => "USD",
                    "CurrencyName" => "US DOLLAR",
                    "Buy" => "23295",
                    "Transfer" => "23295",
                    "Sell" => "23385"
                ]
            ]
        ],
        "Source" => "Joint Stock Commercial Bank for Foreign Trade of Vietnam - Vietcombank"
    ]
];
```

**Example 3**: - *(Convert to Json)*

```
$jsonString = Xml2Array::convert($xmlString)->toJson(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
```

### Convert from array

[](#convert-from-array)

We also have two following methods:

**Convert to XML string**:

```
Array2Xml::convert(array $array)->toXml(bool $prettyOutput = false);
```

**Convert to DOMDocument object**:

```
Array2Xml::convert(array $array)->toDom();
```

**Example 4**:

```
use Jackiedo\XmlArray\Array2Xml;
...

// We will use array from the result of first example as input for this example
$xmlString = Array2Xml::convert($array)->toXml(true);
```

**Example 5**:

```
$domObject = Array2Xml::convert($array)->toDom();
```

Advanced usage
--------------

[](#advanced-usage)

### Set configuration

[](#set-configuration)

If we want to change the settings for the conversion process, we can do it in the following ways:

#### Method 1

[](#method-1)

```
...
$config = [
    'valueKey' => '@text',
    'cdataKey' => '@cdata-section',
    ...
];

$array = Xml2Array::convert($inputXml, $config)->toArray();
...

// And for backward processing
$xml = Array2Xml::convert($inputArray, $config)->toXml();
```

> **Note**: Configuration is an array of parameters. For more details, see section [Default configuration](#default-configuration).

#### Method 2

[](#method-2)

```
$converter = new Xml2Array($config);
$array     = $converter->convertFrom($inputXml)->toArray();
```

#### Method 3

[](#method-3)

```
$converter = new Xml2Array;
$array     = $converter->setConfig($config)->convertFrom($inputXml)->toArray();
```

### Get configuration

[](#get-configuration)

If we implemented the conversion process using methods 2 and 3, we can get configuration of the conversion with method:

```
$config = $converter->getConfig();
```

### Default configuration

[](#default-configuration)

#### For Xml2Array

[](#for-xml2array)

```
$defaultConfig = [
    'version'          => '1.0',         // Version of XML document
    'encoding'         => 'UTF-8',       // Encoding of XML document
    'standalone'       => null,          // Standalone directive for XML document
    'attributesKey'    => '@attributes', // The key name use for storing attributes of node
    'cdataKey'         => '@cdata',      // The key name use for storing value of Cdata Section in node
    'valueKey'         => '@value',      // The key name use for storing text content of node
    'namespacesOnRoot' => true           // Collapse all the namespaces at the root node, otherwise it will put in the nodes for which the namespace first appeared.
];
```

#### For Array2Xml

[](#for-array2xml)

```
$defaultConfig = [
    'version'       => '1.0',         // Version of XML document
    'encoding'      => 'UTF-8',       // Encoding of XML document
    'standalone'    => null,          // Standalone directive for XML document
    'attributesKey' => '@attributes', // The key name use for storing attributes of node
    'cdataKey'      => '@cdata',      // The key name use for storing value of Cdata Section in node
    'valueKey'      => '@value',      // The key name use for storing text content of node
    'rootElement'   => null,          // The name of root node will be create automatically in process of conversion
    'keyFixer'      => true,          // The automatically key normalization will be used during conversion. It can be bool|string|numeric|callable
];
```

### Effect of configuration settings

[](#effect-of-configuration-settings)

#### version

[](#version)

Use inData typeXml2Array, Array2Xmlstring**Effect**: This setting allows specifying the XML version to be generated (in Array2Xml), or reconstructed from the XML string (in Xml2Array)

#### encoding

[](#encoding)

Use inData typeXml2Array, Array2Xmlstring**Effect**: This setting is to indicate the encoding type of the XML to be generated (in Array2Xml), or reconstructed from the XML string (in Xml2Array)

#### standalone

[](#standalone)

Use inData typeXml2Array, Array2Xmlnull**Effect**: This setting is to allow the `standalone` directive to appear in the XML or not. If it is set to `null`, this directive will not appear.

**Example**:

```
$xml = Array2Xml::convert($array, [
    'standalone' => true
])->toXml(true);
```

Content in $xml will be

```

...
```

#### attributesKey, cdataKey, valueKey

[](#attributeskey-cdatakey-valuekey)

Use inData typeXml2Array, Array2Xmlstring**Effect**: This setting allows the use of special keywords to contain the values ​​of properties, CDATA section... during the conversion process.

**Example**: Please review the examples above for more detailed understanding.

#### namespacesOnRoot

[](#namespacesonroot)

Use inData typeXml2Arraybool**Effect**: This setting allows to collect all the parsed XML namespaces and place them in the root node. If it is set to `false`, the namespaces will be located at the nodes where it is declared.

**Example**: We use the `Example 1` above again, but this time the configuration is different:

```
$array = Xml2Array::convert($xmlString, [
    'namespacesOnRoot' => false
])->toArray();
```

After running this piece of code `$array` will contain:

```
$array = [
    "root_node" => [
        "tag"           => "Example tag",
        "attribute_tag" => [
            "@value"      => "Another tag with attributes",
            "@attributes" => [
                "description" => "This is a tag with attribute"
            ]
        ],
        ...
        "example:with_namespace" => [
            "@attributes" => [
                "xmlns:example" => "http://example.com"
            ]
            "example:sub" => "Content"
        ],
    ]
]
```

You see, the `xlmns:example` namespace is put at the `example:with_namespace` key, not at `root_node` as it was originally.

#### rootElement

[](#rootelement)

Use inData typeArray2Xmlstring**Effect**: According to the Well-formed XML standard, the XML content is only allowed to have a single Root node. This setting allows to wrap all the elements of the original array into a single root node, instead of having to manually edit your array.

#### keyFixer

[](#keyfixer)

Use inData typeArray2Xmlbool**Effect**:

According to the Well-formed XML standard, the tag names and attributes must satisfy a number of requirements, in which naming is specified as follows:

- Only allowed to start with aphabet characters and underscore.
- Only accept the `[a-zA-Z]`, `-`, `_`, `.`, `:` characters. In which, the `:` is used to indicate the namespace prefix.
- Do not allow to end with `:`

During conversion, array key names that violate these rules are automatically normalized. If you do not agree to this normalization, set this setting to `false`.

By default, this normalization replaces invalid characters with underscores (`_`). You can change to another character as you like.

**Example**:

```
// Do not use the key normalization
$xml = Array2Xml::convert($array, [
    'keyFixer' => false
])->toXml();

// Use the key normalization with default character (_)
$xml = Array2Xml::convert($array, [
    'keyFixer' => true
])->toXml();

// Replace with '---'
$xml = Array2Xml::convert($array, [
    'keyFixer' => '---'
])->toXml();

// Use a callable for fixing
$xml = Array2Xml::convert($array, [
    'keyFixer' => function ($key) {
        $key = str_replace('/', '_', $key);
        $key = str_replace('\\' , '.', $key);

        return $key;
    }
])->toXml();
```

License
=======

[](#license)

[MIT](LICENSE) © Jackie Do

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance15

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 97.8% 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 ~142 days

Recently: every ~319 days

Total

10

Last Release

1449d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e275bda3c66d969fc06951725fb9baa82b3b0c7eba7e9c4fcf0cf9101c2041c2?d=identicon)[JackieDo](/maintainers/JackieDo)

---

Top Contributors

[![JackieDo](https://avatars.githubusercontent.com/u/9862115?v=4)](https://github.com/JackieDo "JackieDo (45 commits)")[![krzysztofrewak](https://avatars.githubusercontent.com/u/10898728?v=4)](https://github.com/krzysztofrewak "krzysztofrewak (1 commits)")

---

Tags

arrayarray-2-xmlarray-to-xmlconvertxmlxml-2-arrayxml-to-arrayxmlarrayconvertconversionarray-to-xmlxml-to-arrayxml2arrayarray2xmlarraytoxmlxmltoarrayxml-2-arrayarray-2-xml

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[cuyz/valinor

Dependency free PHP library that helps to map any input into a strongly-typed structure.

1.5k9.2M108](/packages/cuyz-valinor)[openlss/lib-array2xml

Array2XML conversion library credit to lalit.org

31052.5M47](/packages/openlss-lib-array2xml)[clearstream/xml-to-array

Incredibly simple XML to array PHP converter

6736.7k](/packages/clearstream-xml-to-array)[digitickets/lalit

GitHub copy of LaLit's XML2Array and Array2XML

721.3M6](/packages/digitickets-lalit)[illuminated/helper-functions

Laravel-specific and pure PHP Helper Functions.

107586.6k7](/packages/illuminated-helper-functions)[ssnepenthe/color-utils

A PHP library for performing SASS-like color manipulations.

631.1M10](/packages/ssnepenthe-color-utils)

PHPackages © 2026

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