PHPackages                             skraeda/xmlary - 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. skraeda/xmlary

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

skraeda/xmlary
==============

Collection of utilities to work with XML

v1.4.0(5y ago)01.3k↓50%MITPHPPHP &gt;=7.2CI failing

Since May 7Pushed 5y ago2 watchersCompare

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

READMEChangelog (1)Dependencies (3)Versions (9)Used By (0)

Xmlary
======

[](#xmlary)

[![CircleCI](https://camo.githubusercontent.com/21405624ebdcd6bfe6d38796b6bc950fa91f66f5339efa1b42e93884a05dd28b/68747470733a2f2f696d672e736869656c64732e696f2f636972636c6563692f6275696c642f6769746875622f536b72616564612f786d6c617279)](https://camo.githubusercontent.com/21405624ebdcd6bfe6d38796b6bc950fa91f66f5339efa1b42e93884a05dd28b/68747470733a2f2f696d672e736869656c64732e696f2f636972636c6563692f6275696c642f6769746875622f536b72616564612f786d6c617279)[![Codecov](https://camo.githubusercontent.com/eabde3faaee7d66a12a7c2cba196ae02170e29e5cc78fc09880cfb05d6169c63/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f536b72616564612f786d6c617279)](https://camo.githubusercontent.com/eabde3faaee7d66a12a7c2cba196ae02170e29e5cc78fc09880cfb05d6169c63/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f536b72616564612f786d6c617279)[![Version Badge](https://camo.githubusercontent.com/514eaa5accda1c24e90f402c56497d65d39a93bbe21d70afb62612b4477dd994/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736b72616564612f786d6c617279)](https://camo.githubusercontent.com/514eaa5accda1c24e90f402c56497d65d39a93bbe21d70afb62612b4477dd994/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736b72616564612f786d6c617279)[![License Badge](https://camo.githubusercontent.com/1d7da4d721f1d9e06ab03d7b048f844c19aa7657bc20e4efc7241daa67378caf/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f536b72616564612f786d6c6172793f636f6c6f723d316635396334)](https://camo.githubusercontent.com/1d7da4d721f1d9e06ab03d7b048f844c19aa7657bc20e4efc7241daa67378caf/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f536b72616564612f786d6c6172793f636f6c6f723d316635396334)

This package is a set of XML utilities for PHP.

Writer examples
---------------

[](#writer-examples)

Examples of how the writer converts arrays to XML.

Use `toString` to get the XML body string or `toDomDocument` to get a PHP DOMDocument object.

### Basic elements

[](#basic-elements)

```
use Skraeda\Xmlary\XmlWriter;

$writer = new XmlWriter;

$array = [
    'People' => [
        // String value should become Unknown
        'Marie' => 'Unknown',

        // Null value should become
        'Lao' => null,

        // Boolean value should become 1
        'Peter' => true,

        // Nested value should become 20
        'John' => [
            'Age' => 20,
        ]
    ]
];

echo $writer->toString($array);
```

outputs

```

    Unknown

    1

        20

```

### Array elements

[](#array-elements)

```
$array = [
    'Root' => [
        'ArrayOfValues' => [
            // Should create duplicate  elements
            'Values' => [
                'String1',
                2,
                true,
                null
            ]
        ],
        'ArrayOfNestedValues' => [
            // Should create duplicate  elements
            'Values' => [
                [
                    'StringValue' => 'String1'
                ],
                [
                    'BoolValue' => true
                ],
                [
                    'NullValue' => null
                ],
                [
                    'NumericValue' => 123
                ],
                [
                    'Nested' => [1, 2]
                ]
            ]
        ]
    ]
];

echo $writer->toString($array);
```

outputs

```

        String1
        2
        1

            String1

            1

            123

            1
            2

```

Writer configuration
--------------------

[](#writer-configuration)

This section describes some ways you can customize the `XmlWriter`. You can configure the XmlWriter through interfaces, configure the inner `DOMDocument` object before or after generation or add `keywords` to handle individual elements differently.

### Interfaces

[](#interfaces)

You can set a custom configuration object, validator or value converter via the `XmlWriter` constructor or through setter methods.

#### Example

[](#example)

```
use Skraeda\Xmlary\Contracts\XmlValueConverterContract;

/**
 * Custom value converter to change boolean values to true / false strings instead of 1 / 0
 */
class CustomXmlValueConverter implements XmlValueConverterContract
{
    public function convert($value)
    {
        if (is_bool($value)) {
            return $value ? 'true' : 'false';
        }
        return $value;
    }
}

// Outputs false
echo (new XmlWriter)
    ->setConverter(new CustomXmlValueConverter)
    ->toString(['Root' => false]);
```

### Middleware

[](#middleware)

You can add middleware before or after `DOMDocument` creation.

#### Example

[](#example-1)

```
// Add namespaced attribute to root element.
$writer->pushAfterMiddleware(function ($doc) {
    $namespace = $doc->createAttributeNS('http://example.com', 'example:attr');
    $namespace->value = 'foo';
    $doc->firstChild->appendChild($namespace);
});

// Outputs value
$writer->toString(['foo:Root' => 'value']);
```

### Keywords

[](#keywords)

Extend the `XmlWriter` with Keywords to add some custom functionality on the element level.

#### Example

[](#example-2)

```
use Skraeda\Xmlary\Contracts\XmlKeyword;

class CDataKeyword implements XmlKeyword
{
    public function handle(DOMDocument $doc, DOMNode $parent, $value): void
    {
        $parent->appendChild($doc->createCDATASection($value));
    }
}

echo $writer->extend('cdata', new CDataKeyword)->toString([
    'Root' => [
        'Element' => [
            '@cdata' => 'bar',
        ]
    ]
]);
```

outputs

```
bar]]>
```

### Bootstrap

[](#bootstrap)

You can use the `bootstrap` method on the writer to configure it with default keywords.

#### Keywords

[](#keywords-1)

- `attributes`: Set element attributes
- `value`: Set element value (Useful if using other keywords in the same node)
- `cdata`: Wraps a value in CDATA block
- `comment`: Wraps a value in comment block
- `handler`: Add a customer function handler for a node block

#### Example

[](#example-3)

```
$writer = (new XmlWriter)->bootstrap();

$arr = [
    'Root' => [
        '@attributes' => [
            'xmlns:example' => 'http://example.com',
            'example:attr' => 'foo'
        ],
        'Element' => [
            '@attributes' => [
                'foo' => 'bar'
            ],
            '@value' => 'Value'
        ],
        'CData' => [
            '@cdata' => 'Wrapped',
            '@value' => 'NotWrapped'
        ],
        'Comment' => [
            '@value' => 'Value',
            '@comment' => 'Comment'
        ],
        'Handler' => [
            '@handler' => function (DOMDocument $doc, DOMNode $parent) {
                $parent->appendChild($doc->createElement('Name', 'Value'));
            }
        ]
    ]
];

echo $writer->toString($arr);
```

Reader examples
---------------

[](#reader-examples)

Examples of how the reader converts XML to arrays.

### Example 1

[](#example-1-1)

```
$xml =  [
        'Element' => [
            '@attributes' => [
                'id' => '1'
            ],
            '@value' => Value
        ]
    ]
]
```

### Example 2

[](#example-2-1)

```
$xml =
            Misc

XML;
```

outputs

```
[
    'Order' => [
        'Items' => [
            'Item' => [
                [
                    '@attributes' => [
                        'id' => 1
                    ],
                    'Price' => [
                        '@value' => '2.00'
                    ],
                    'Supplier' => [
                        'Organization' => [
                            'OrganizationName' => [
                                '@value' => null
                            ]
                        ]
                    ]
                ],
                [
                    '@attributes' => [
                        'id' => 3
                    ],
                    'Price' => [
                        '@value' => '1.00'
                    ]
                    'Type' => [
                        '@value' => 'Misc'
                    ],
                    'Supplier' => [
                        '@value' => null
                    ]
                ]
            ]
        ]
    ]
]
```

### Example 3

[](#example-3-1)

You can provide a configuration mapping for the nodes for some basic changes to the generated array.

```
use Skraeda\Xmlary\XmlReaderNodeConfiguration as Config;

$xml =  [
        // Provide config to rename Root element
        '@config' => new Config('NewRoot'),
        'Element' => [
            // Provide config to ensure Element is always an array element and add custom value converter to cast to int and add +2 to the value.
            '@config' => new Config(null, true, function ($oldValue) {
                return ((int) $oldValue) + 2;
            })
        ],
        'Inner' => [
            '@config' => new Config(null, false, function ($oldValue) use ($reader) {
                return $reader->parse(html_entity_decode($oldValue));
            }, function (XmlReaderNode $node) {
                // Callback handler to execute when the ReaderNode is created..
            })
        ]
    ]
];

$reader->parse($xml, $config);
```

outputs

```
[
    'NewRoot' => [
        'Element' => [
            [
                '@value' => 3
            ]
        ],
        'Inner' => [
            '@value' => [
                'Sheet' => [
                    'Data' => [
                        '@value' => '2'
                    ]
                ]
            ]
        ]
    ]
]
```

You can create custom config classes to reduce repitition if you need.

Either extend the reader node configuration class or implement the interface.

Reader configuration
--------------------

[](#reader-configuration)

This section describes how you can customize the `XmlReader`.

### Interfaces

[](#interfaces-1)

You can set a custom configuration object through the constructor or setter methods.

Utilities
---------

[](#utilities)

### XmlSerializable

[](#xmlserializable)

Interface you can define on a model so it can be formatted as XML by an `XmlWriter`.

You need to define `xmlSerialize` on your model which should return an array similar to the above examples.

### XmlSerialize

[](#xmlserialize)

Trait you can add on a model to give it a default `xmlSerialize` handler using reflection.

### XmlMessage

[](#xmlmessage)

Abstract base class you can extend to give your object a default `xmlSerialize` handler using reflection.

#### Example

[](#example-4)

```
use Skraeda\Xmlary\XmlMessage;

class MyMessage extends XmlMessage
{
    public $Public = 'PublicValue';

    protected $Protected = 'ProtectedValue';

    private $Private = 'PrivateValue';

    public $Array;

    public $Inner;

    public $Changer = 'WillBeChanged';

    public $Attrs = null;

    public function __construct(?MyMessage $Inner = null)
    {
        $this->Array = ['Field' => 'Value'];
        $this->Inner = $Inner;
    }

    protected function ChangerMutator()
    {
        return 'ChangedValue';
    }

    // Uses AttributeKeyword and ValueKeyword
    protected function AttrsAttributes()
    {
        return [
            'value' => 'AttributeValue'
        ];
    }

    protected function AttrsTag()
    {
        return 'AttributeTag';
    }

    protected function attributes()
    {
        return [
            'foo' => 'bar'
        ];
    }
}

echo $writer->toString(new MyMessage(new MyMessage));
```

outputs

```

    PublicValue
    ProtectedValue
    PrivateValue

        Value

            PublicValue
            ProtectedValue
            PrivateValue

                Value

            ChangedValue

    ChangedValue

```

Development
-----------

[](#development)

PHP7.2 CLI dockerfile included, use it to test any new functionality.

### Start

[](#start)

```
docker-compose up
```

### Test

[](#test)

```
docker-compose exec app vendor/bin/phpunit
```

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 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 ~35 days

Recently: every ~10 days

Total

8

Last Release

1952d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/15886771?v=4)[Gunnar Örn Baldursson](/maintainers/Gunsobal)[@Gunsobal](https://github.com/Gunsobal)

---

Top Contributors

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

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/skraeda-xmlary/health.svg)

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

###  Alternatives

[magento/composer

Magento composer library helps to instantiate Composer application and run composer commands.

317.7M8](/packages/magento-composer)[enlitepro/zf2-scaffold

1022.5k3](/packages/enlitepro-zf2-scaffold)

PHPackages © 2026

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