PHPackages                             jeckerson/array2xml - 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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. jeckerson/array2xml

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

jeckerson/array2xml
===================

Array -&gt; XML Converter Class

v1.0.0(5y ago)326521[3 issues](https://github.com/Jeckerson/array2xml/issues)BSD-3-ClausePHPPHP &gt;=5.4CI failing

Since Aug 6Pushed 5y ago5 watchersCompare

[ Source](https://github.com/Jeckerson/array2xml)[ Packagist](https://packagist.org/packages/jeckerson/array2xml)[ RSS](/packages/jeckerson-array2xml/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

\[PHP\] Array to XML
====================

[](#php-array-to-xml)

Array2xml is a PHP library that converts array to valid XML.

Based on [XMLWriter](http://php.net/manual/en/book.xmlwriter.php).

Requirements
------------

[](#requirements)

- PHP 5.3+
- XMLWriter

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

[](#installation)

```
require_once ('/path/to/array2xml.php');

```

Usage (Ex.: RSS Last News)
--------------------------

[](#usage-ex-rss-last-news)

Load the library and set custom configuration:

```
$array2xml = new Array2xml();
$array2xml->setRootName('rss');
$array2xml->setRootAttrs(array('version' => '2.0'));
$array2xml->setCDataKeys(array('description'));

```

Start by creating a root element:

```
$data['channel']['title']        = 'News RSS';
$data['channel']['link']         = 'http://yoursite.com/';
$data['channel']['description']  = 'Amazing RSS News';
$data['channel']['language']     = 'en';

```

Now pass elements from DB query in cycle:

```
$row = $db->lastNews();
foreach($row as $key => $lastNews)
{
	$data['channel'][$key]['item']['title']       = $lastNews->title;
	$data['channel'][$key]['item']['link']        = 'http://yoursite.com/news/'.$lastNews->url;
	$data['channel'][$key]['item']['description'] = $lastNews->description;
	$data['channel'][$key]['item']['pubDate']     = date(DATE_RFC1123, strtotime($lastNews->added));
}

```

You can also set element attributes individually. The example below appends an attribute `AttributeName` to `item` node:

```
$data['channel'][$key]['item']['@attributes'] 		= array('AttributeName' => $attributeValue);

```

Or, if your node doesn't have children, you can use this:

```
$data['channel]['@attributes'] = array('AttributeName' => $attributeValue);
$data['channel]['@content']    = 'Content of channel node';

```

This will set both attributes and the content of `channel` node.

Alternatively, you can use setElementsAttrs() method:

```
$array2xml->setElementsAttrs( array('ElementName' => array('AttributeName' => $attributeValue) ));

```

*Note that in this case all elements with specified names will have identical attribute names and values.*

If you need to include a raw XML tree somewhere, mark it's element using `$array2xml->setRawKeys(array('elementName'))`

Finally, convert and print output data to screen

```
echo $array2xml->convert($data);

```

Configuration
-------------

[](#configuration)

You can easily configure this lib to fit your specific use case using setters described below.

#### setVersion(string $version)

[](#setversionstring-version)

Sets XML version header.

#### setEncoding(string $encoding)

[](#setencodingstring-encoding)

Sets XML encoding

#### setRootName(string $rootName)

[](#setrootnamestring-rootname)

Set XML Root Element Name

#### setRootAttrs(array $rootAttrs)

[](#setrootattrsarray-rootattrs)

Set XML Root Element Attributes

#### setElementsAttrs(array $attrs)

[](#setelementsattrsarray-attrs)

Set Attributes of every XML Elements that matches the given names. Example argument: `['elementName' => ['someAttr' => 'attrValue']]`

#### setCDataKeys(array $elementNames)

[](#setcdatakeysarray-elementnames)

Marking given elements as CData ones

#### setRawKeys(array $elementNames)

[](#setrawkeysarray-elementnames)

Marking given elements as raw ones

#### setNumericTagPrefix(string $prefix)

[](#setnumerictagprefixstring-prefix)

Set default prefix for numeric nodes

#### setSkipNumeric(bool $skipNumeric)

[](#setskipnumericbool-skipnumeric)

On/Off Skip numeric nodes

#### setEmptyElementSyntax(const)

[](#setemptyelementsyntaxconst)

In some cases you might want to control the exact syntax of empty elements.

By default, nodes that are empty or equal to null are using self-closing syntax(``).

You can override this behavior using `Array2xml::EMPTY_FULL` to force using closing tag(``).

Available agruments are `Array2xml::EMPTY_SELF_CLOSING` or `Array2xml::EMPTY_FULL`

#### setFilterNumbersInTags(bool|array $data)

[](#setfilternumbersintagsboolarray-data)

Remove numbers from element names.

Possible args are:

- `boolean TRUE` to remove numbers from ALL elements
- `array` contains node names that need filtering.

This is a easy workaround to have identically named elements in your XML built from an array.

For example, let's build an XML with 3 `image` nodes:

```
//list of our images
$images = array('image1.jpg', 'image3.jpg', 'image3.jpg');
// input array
$data = array();
for($i=0;$isetFilterNumbersInTags(array('image'));

$xml = array2xml->convert($data);

```

That's it! Now we have a nasty XML with 3 identically named nodes in it.

Testing
-------

[](#testing)

```
phpunit Tests/Array2xmlTest.php

```

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 61.4% 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

Unknown

Total

1

Last Release

2111d ago

### Community

Maintainers

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

---

Top Contributors

[![Jeckerson](https://avatars.githubusercontent.com/u/3289702?v=4)](https://github.com/Jeckerson "Jeckerson (27 commits)")[![okwinza](https://avatars.githubusercontent.com/u/108925?v=4)](https://github.com/okwinza "okwinza (12 commits)")[![uldisn](https://avatars.githubusercontent.com/u/3525344?v=4)](https://github.com/uldisn "uldisn (4 commits)")[![overbid](https://avatars.githubusercontent.com/u/529623?v=4)](https://github.com/overbid "overbid (1 commits)")

---

Tags

phpxml

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jeckerson-array2xml/health.svg)

```
[![Health](https://phpackages.com/badges/jeckerson-array2xml/health.svg)](https://phpackages.com/packages/jeckerson-array2xml)
```

###  Alternatives

[m1/vars

Vars is a simple to use and easily extendable configuration loader with in built loaders for ini, json, PHP, toml, XML and yaml/yml file types. It also comes with in built support for Silex and more frameworks to come soon.

69124.2k1](/packages/m1-vars)[goetas/xsd2php-runtime

Convert XSD (XML Schema) definitions into PHP classes

493.3k](/packages/goetas-xsd2php-runtime)[bupy7/xml-constructor

The array-like constructor of XML document structure.

1337.9k](/packages/bupy7-xml-constructor)

PHPackages © 2026

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