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

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

mleczek/xml
===========

Transform PHP object to XML

v1.2.0(9y ago)1881MITPHP

Since Jan 11Pushed 9y ago1 watchersCompare

[ Source](https://github.com/mleczek/xml)[ Packagist](https://packagist.org/packages/mleczek/xml)[ Docs](https://github.com/mleczek/xml)[ RSS](/packages/mleczek-xml/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (2)Versions (4)Used By (1)

Convert PHP objects to XML
==========================

[](#convert-php-objects-to-xml)

[![Latest Stable Version](https://camo.githubusercontent.com/578e44c21f95966bad368d11f311b3371c8e993c52034d6349eedc948e6c249a/68747470733a2f2f706f7365722e707567782e6f72672f6d6c65637a656b2f786d6c2f762f737461626c65)](https://packagist.org/packages/mleczek/xml)[![Build Status](https://camo.githubusercontent.com/84ea77fb20c71ef6fcafd73de69598d1a744790f4f03576bfefb4c1188d7d2ce/68747470733a2f2f7472617669732d63692e6f72672f6d6c65637a656b2f786d6c2e737667)](https://travis-ci.org/mleczek/xml)[![Coverage Status](https://camo.githubusercontent.com/4b46d1e72ac8ee12d64e8c58cf4c786535113d56ded8ee801c44306e80fcf38a/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6d6c65637a656b2f786d6c2f62616467652e7376673f6272616e63683d312e30)](https://coveralls.io/github/mleczek/xml?branch=1.0)[![License](https://camo.githubusercontent.com/3dfe18140088e89e1a0854e5323bcacba33bc2a02d6e30c5e5bb96c9e26a6ea9/68747470733a2f2f706f7365722e707567782e6f72672f6d6c65637a656b2f786d6c2f6c6963656e7365)](https://packagist.org/packages/mleczek/xml)

The goal of the this library is to provide an easy way to respond XML by REST API.

- [Installation](#installation)
- [Basic concepts](#basic-concepts)
- [XML Body](#xml-body)
    - [Array](#array)
        - [Elements](#elements)
        - [Attributes](#attributes)
    - [String](#string)
    - [XmlElement](#xmlelement)
- [XML Declaration](#xml-declaration)
- [Contributing](#contributing)
- [License](#license)

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

[](#installation)

Require this package with composer:

```
composer require mleczek/xml

```

Basic concepts
--------------

[](#basic-concepts)

Class may be converted to XML using `Mleczek\Xml\XmlConverter` which implements the `__toString`, `outerXml` and `innerXml` methods returning XML as string:

```
$dog = new Dog();
$converter = new XmlConverter($dog);
$outerXml = (string)$converter;
$outerXml = $converter->outerXml(); // equals __toString
$innerXml = $converter->innerXml();
```

Library contains also the shorthand to cast objects to XML string using `Mleczek\Xml\XmlConvertible` trait (or helper functions):

```
use Mleczek\Xml\Xmlable;
use Mleczek\Xml\XmlConvertible;

class Dog
{
    use XmlConvertible;

    public $id = 5;
}
```

`Mleczek\Xml\XmlConvertible` implements the `toXml` method (also available as a helper function) which returns the outer XML string (skipped `` part in examples for better readability):

```
$dog = new Dog();
$xml = $dog->toXml(); // returns 5
$xml = toXml($dog);   // without using XmlConvertible trait
```

By default root elements is ``, you can change it calling `toXmlAs` method:

```
$dog = new Dog();
$xml = $dog->toXmlAs('dog'); // returns 5
$xml = toXmlAs($dog, 'dog'); // without using XmlConvertible trait
```

Above examples use `Mleczek\Xml\StructureAnalyser` class to determine the output XML structure, to get more control you can implement the `Mleczek\Xml\Xmlable` interface with `xml` method:

```
use Mleczek\Xml\Xmlable;

class Dog implements Xmlable
{
    public function xml()
    {
        // XML Body...
    }
}
```

The [XML body](#xml-body) describes the ouput XML and will be described in the next chapter. Also the `toXml` method accepts optionally one argument ([array](#array)) which can be used to control the [XML body](#xml-body) structure:

```
$dog = new Dog();
$xml = $dog->toXml(['cat']); // returns
```

XML Body
--------

[](#xml-body)

This chapter describe the data which should by returned by the `xml` method.

XML Body can be implemented using 3 ways:

- [Array](#array) - meta description
- [String](#string) - plain XML string
- [XmlElement](#xmlelement)

### Array

[](#array)

The meta language which allow defining XML body, including:

- [Elements](#elements)
- [Attributes](#attributes)

#### Elements

[](#elements)

The basic example return self-closing root element:

```
public function xml()
{
    //
    return ['dog'];
}
```

You can add `` node to the `` root using:

```
public function xml()
{
    // {$this->full_name}
    return [
        'dog' => [
            'name' => 'full_name'
        ]
    ];
}
```

As you can see above if you define value equal `full_name` then **`XmlConverter` will look for `full_name` property in the object** (casted to string). If property stores other object or array then you can **retrieve nested property/key using dot notation** `address.city` (equals `$this->address->city` or `$this->address['city']`).

You can also define more elements, **self-closing elements** and **constant values**:

```
public function xml()
{
    // 5
    return [
        'dog' => [
            'hau',          // self-closing element
            'hau2' => null, // self-closing element #2
            'id' => '=5',   // use "=" prefix for constant values
        ]
    ];
}
```

You can also **merge arrays** (without using PHP functions) and use **conditional output**:

```
public function xml()
{
    $extra_elements = [];
    if($this->isSuperDog()) {
        $extra_elements = ['hau_power' => 5];
    }

    // $this->isSuperDog():
    // true: 5
    // false:
    return [
        'dog' => [
            'hau' => true,   // true -> self-closing element
            'miau' => false, // false -> skip element
            $extra_elements, // merge arrays
        ]
    ];
}
```

#### Attributes

[](#attributes)

Attributes works like the elements, the only difference is that you have to **prepend the name with *"@"* prefix**.

```
public function xml()
{
    //
    return [
        'dog' => [
            '@name' => 'full_name'
            '@canHau',            // without value
            '@id' => '=5',        // use "=" prefix for constant values
        ]
    ];
}
```

Of course you can mix elements with attributes:

```
public function xml()
{
    // 5
    return [
        'dog' => [
            '@canHau',
            'id' => '=5'
        ]
    ];
}
```

### String

[](#string)

Build and return plain XML string:

```
use Mleczek\Xml\Xmlable;

class Dog implements Xmlable
{
    public function xml()
    {
        return '';
    }
}
```

### XmlElement

[](#xmlelement)

**Not recommended** and not documented. See [source code](https://github.com/mleczek/xml/blob/master/src/XmlElement.php) for more information.

XML Declaration
---------------

[](#xml-declaration)

Using `toXml` method provided with `Mleczek\Xml\XmlConvertible` trait (or equivalent helper functions) automatically add XML declaration:

```

```

Above declaration is available as constant value at `Mleczek\Xml\XmlElement::XmlDeclaration`.

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

[](#contributing)

Thank you for considering contributing! If you would like to fix a bug or propose a new feature, you can submit a Pull Request.

License
-------

[](#license)

The library is licensed under the [MIT license](https://opensource.org/licenses/MIT).

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~4 days

Total

3

Last Release

3402d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/143e31568d2a8cef787b416fd2b5f10b78d28cb141ffe049c197d7fb31dc911c?d=identicon)[mleczek](/maintainers/mleczek)

---

Top Contributors

[![mleczek](https://avatars.githubusercontent.com/u/15350415?v=4)](https://github.com/mleczek "mleczek (30 commits)")

---

Tags

obj2xmlphpxmlphpxmlconvertobjecttransform

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

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