PHPackages                             alexstar/xmlmaker - 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. alexstar/xmlmaker

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

alexstar/xmlmaker
=================

A flexible PHP class for dynamic XML generation with support for attributes, repeating elements (@items), and pretty-printed output.

1.0.0(7mo ago)01MITPHPPHP &gt;=7.4

Since Sep 26Pushed 7mo agoCompare

[ Source](https://github.com/AlexSuperStar/XmlMaker)[ Packagist](https://packagist.org/packages/alexstar/xmlmaker)[ Docs](https://github.com/AlexSuperStar/XmlMaker)[ RSS](/packages/alexstar-xmlmaker/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (3)Used By (0)

XmlMaker
========

[](#xmlmaker)

[![PHP](https://camo.githubusercontent.com/ce0c70c519047d0e507604f03e6e8ae6c27bcc072027e899680d9bf93804dc76/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d372e342532422d626c7565)](https://www.php.net/)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)

A flexible PHP class for dynamic XML generation with support for attributes, repeating elements (`@items`), and pretty-printed output.

> Author: Alexey Starikov
> Inspired by [JsonMaker](https://github.com/AlexSuperStar/jsonMaker)

---

> 🇷🇺 Документация на русском | [🇬🇧 English version](#english)

---

Русский
-------

[](#русский)

### ✨ Возможности

[](#-возможности)

- Создание XML через объектный (`$xml->tag = 'value'`) или массивный (`$xml['tag'] = 'value'`) синтаксис
- Задание атрибутов через зарезервированный ключ `@attributes`
- Генерация повторяющихся элементов:
    - Через `parse()` с `@items`
    - Через метод `addItem()`
- Форматированный XML с отступами (`toPrettyXml()`)
- Полная поддержка UTF-8 (включая кириллицу)
- Автоматическое экранирование текста
- Без внешних зависимостей
- Совместимость с PHP 7.4+

### 📦 Установка

[](#-установка)

#### Вариант 1: Прямое подключение

[](#вариант-1-прямое-подключение)

Скачайте `XmlMaker.php` и подключите:

```
require_once 'XmlMaker.php';
```

#### Вариант 2: Через Composer

[](#вариант-2-через-composer)

```
composer require alexstar/xmlmaker
```

Затем в коде:

```
require 'vendor/autoload.php';
use alexstar\XmlMaker;
```

### 🚀 Примеры использования

[](#-примеры-использования)

#### 1. Простой XML

[](#1-простой-xml)

```
$xml = new \alexstar\XmlMaker('config');
$xml->host = 'localhost';
$xml->port = 5432;

echo $xml->toPrettyXml();
```

**Результат:**

```

  localhost
  5432

```

#### 2. Атрибуты

[](#2-атрибуты)

```
$xml->item->{"@attributes"}["id"] = "101";
$xml->item->name = "Товар";
```

→ `Товар`

Или через `parse()`:

```
$xml->parse([
    'item' => [
        '@attributes' => ['id' => '101'],
        'name' => 'Товар'
    ]
]);
```

#### 3. Повторяющиеся элементы через `@items` (в `parse()`)

[](#3-повторяющиеся-элементы-через-items-в-parse)

```
$xml->parse([
    'ИнфПолФХЖ1' => [
        '@items' => [
            'ТекстИнф' => [
                ['@attributes' => ['Идентиф' => 'номер_акта',    'Значен' => 'ПРМ1123456-1']],
                ['@attributes' => ['Идентиф' => 'дата_акта',     'Значен' => '07.05.2025']],
                ['@attributes' => ['Идентиф' => 'номер_заказа',  'Значен' => 'ПРМЗАК-123']],
                ['@attributes' => ['Идентиф' => 'дата_заказа',   'Значен' => '03.05.2024']],
            ]
        ]
    ]
]);
```

**Результат:**

```

```

#### 4. Повторяющиеся элементы через `addItem()`

[](#4-повторяющиеся-элементы-через-additem)

```
$xml->ИнфПолФХЖ1
    ->addItem('ТекстИнф', ['@attributes' => ['Идентиф' => 'номер_акта', 'Значен' => 'ПРМ1123456-1']])
    ->addItem('ТекстИнф', ['@attributes' => ['Идентиф' => 'дата_акта',  'Значен' => '07.05.2025']]);
```

→ То же, что и выше. Метод поддерживает цепочку вызовов.

### ⚠️ Важно

[](#️-важно)

- Зарезервированные ключи: `@attributes`, `@items`
- Все данные должны быть в кодировке **UTF-8**
- Пустые элементы с атрибутами выводятся как самозакрывающиеся теги
- Класс реализует `ArrayAccess`, `Countable`, `IteratorAggregate`

---

English
-------

[](#english)

> 🇬🇧 English documentation | [🇷🇺 Версия на русском](#%D1%80%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)

### ✨ Features

[](#-features)

- Build XML using object (`$xml->tag = 'value'`) or array (`$xml['tag'] = 'value'`) syntax
- Set XML attributes via reserved key `@attributes`
- Generate repeating elements:
    - Via `parse()` with `@items`
    - Via `addItem()` method (chainable)
- Pretty-printed XML output with indentation (`toPrettyXml()`)
- Full UTF-8 support (including Cyrillic)
- Automatic text escaping
- No external dependencies
- PHP 7.4+ compatible

### 📦 Installation

[](#-installation)

#### Option 1: Direct include

[](#option-1-direct-include)

Download `XmlMaker.php` and include:

```
require_once 'XmlMaker.php';
```

#### Option 2: Via Composer

[](#option-2-via-composer)

```
composer require alexstar/xmlmaker
```

Then in your code:

```
require 'vendor/autoload.php';
use alexstar\XmlMaker;
```

### 🚀 Usage Examples

[](#-usage-examples)

#### 1. Basic XML

[](#1-basic-xml)

```
$xml = new \alexstar\XmlMaker('config');
$xml->host = 'localhost';
$xml->port = 5432;

echo $xml->toPrettyXml();
```

**Output:**

```

  localhost
  5432

```

#### 2. Attributes

[](#2-attributes)

```
$xml->item->{"@attributes"}["id"] = "101";
$xml->item->name = "Product";
```

→ `Product`

Or via `parse()`:

```
$xml->parse([
    'item' => [
        '@attributes' => ['id' => '101'],
        'name' => 'Product'
    ]
]);
```

#### 3. Repeating Elements with `@items` (in `parse()`)

[](#3-repeating-elements-with-items-in-parse)

```
$xml->parse([
    'InfoBlock' => [
        '@items' => [
            'TextInfo' => [
                ['@attributes' => ['Ident' => 'doc_number', 'Value' => 'PRM1123456-1']],
                ['@attributes' => ['Ident' => 'doc_date',  'Value' => '07.05.2025']],
                ['@attributes' => ['Ident' => 'order_number', 'Value' => 'PRMZAK-123']],
                ['@attributes' => ['Ident' => 'order_date',  'Value' => '03.05.2024']],
            ]
        ]
    ]
]);
```

**Result:**

```

```

#### 4. Repeating Elements with `addItem()`

[](#4-repeating-elements-with-additem)

```
$xml->InfoBlock
    ->addItem('TextInfo', ['@attributes' => ['Ident' => 'doc_number', 'Value' => 'PRM1123456-1']])
    ->addItem('TextInfo', ['@attributes' => ['Ident' => 'doc_date',  'Value' => '07.05.2025']]);
```

→ Same result. Chainable.

### ⚠️ Notes

[](#️-notes)

- Reserved keys: `@attributes`, `@items`
- Input data must be in **UTF-8**
- Empty elements with attributes are rendered as self-closing tags
- Implements `ArrayAccess`, `Countable`, `IteratorAggregate`

---

### 📜 License

[](#-license)

MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance62

Regular maintenance activity

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

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

Total

2

Last Release

234d ago

Major Versions

0.9.0 → 1.0.02025-09-26

### Community

Maintainers

![](https://www.gravatar.com/avatar/73d4ab61fee858c2ae8f6d92171eef2d2078d8e405a73e411817631478df6044?d=identicon)[AlexSuperStar](/maintainers/AlexSuperStar)

---

Top Contributors

[![AlexSuperStar](https://avatars.githubusercontent.com/u/1777761?v=4)](https://github.com/AlexSuperStar "AlexSuperStar (2 commits)")

---

Tags

phpxmlutf8attributesxml-builderxml generator

### Embed Badge

![Health badge](/badges/alexstar-xmlmaker/health.svg)

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

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