PHPackages                             tourze/xml-helper - 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. tourze/xml-helper

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

tourze/xml-helper
=================

XML处理助手工具，提供XML解析、生成和处理功能

0.0.1(1y ago)03.5k3MITPHPPHP ^8.1CI passing

Since Mar 24Pushed 4mo ago1 watchersCompare

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

READMEChangelog (1)DependenciesVersions (2)Used By (3)

XML Helper
==========

[](#xml-helper)

[English](README.md) | [中文](README.zh-CN.md)

[![PHP Version](https://camo.githubusercontent.com/bcf50cefa0ed4033f973e6015095e7c4b25395d47b88042dbaab3f0727e8180d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f786d6c2d68656c7065722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/xml-helper)[![Latest Version](https://camo.githubusercontent.com/0d6dec7b4a16bef6e1a353a6cb3b67737185f4d0eb25f8b0bcf08eb68a90aa89/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f786d6c2d68656c7065722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/xml-helper)[![Total Downloads](https://camo.githubusercontent.com/36ea208956e65b06a05b9ae43606a1dd17d0b59e47c5e38a9ea630ce64c549e0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f75727a652f786d6c2d68656c7065722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/xml-helper)[![License](https://camo.githubusercontent.com/8783cbc3ed8cc11fedfa02826467ff07c6fe2b3144a4c9acff103330cf7e8218/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f75727a652f786d6c2d68656c7065722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/xml-helper)[![Build Status](https://camo.githubusercontent.com/df27d0d88386d1271e6f8f78f2cb99236da84ee142e7293fd76809349172820d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6f776e65722f7265706f2f63692e796d6c3f7374796c653d666c61742d737175617265)](https://github.com/owner/repo/actions)[![Code Coverage](https://camo.githubusercontent.com/bd69c0d30f47618ad228841b105aeb582191bcf1218fe05d356e1deab427fc3b/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f6f776e65722f7265706f3f7374796c653d666c61742d737175617265)](https://codecov.io/gh/owner/repo)

A lightweight PHP library for simple XML parsing and generation. Provides convenient methods to convert between XML strings and PHP arrays.

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Requirements](#requirements)
- [Features](#features)
- [Quick Start](#quick-start)
    - [Import the namespace](#import-the-namespace)
    - [Convert XML to Array](#convert-xml-to-array)
    - [Convert Array to XML](#convert-array-to-xml)
- [Documentation](#documentation)
    - [XML::parse()](#xmlparse)
    - [XML::build()](#xmlbuild)
    - [XML::cdata()](#xmlcdata)
    - [XML::sanitize()](#xmlsanitize)
- [Advanced Usage](#advanced-usage)
    - [Custom Configuration](#custom-configuration)
    - [Performance Optimization](#performance-optimization)
- [Example Use Cases](#example-use-cases)
    - [Working with API Responses](#working-with-api-responses)
    - [Handling Complex Structures](#handling-complex-structures)
- [Contributing](#contributing)
- [Testing](#testing)
- [License](#license)

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

[](#installation)

```
composer require tourze/xml-helper
```

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

[](#requirements)

- PHP &gt;= 8.1
- ext-simplexml
- ext-libxml

Features
--------

[](#features)

- Convert XML strings to PHP arrays
- Convert PHP arrays to XML strings
- CDATA support for handling special characters
- XML sanitization to remove invalid characters
- Simple and intuitive API
- Customizable root and child node names
- Support for XML attributes
- Special boolean value handling

Quick Start
-----------

[](#quick-start)

### Import the namespace

[](#import-the-namespace)

```
use Tourze\XML\XML;
```

### Convert XML to Array

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

```
$xml = '25';
$array = XML::parse($xml);

// Result:
// [
//     'name' => 'John Doe',
//     'age' => '25'
// ]
```

### Convert Array to XML

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

```
$array = [
    'name' => 'John Doe',
    'age' => 25
];

$xml = XML::build($array);
// Result: 25
```

Documentation
-------------

[](#documentation)

### XML::parse()

[](#xmlparse)

Parses an XML string into a PHP array.

```
$xml = 'Alice30';
$array = XML::parse($xml);
```

### XML::build()

[](#xmlbuild)

Converts a PHP array to an XML string.

Parameters:

- `$data`: The array to convert
- `$root`: Root element name (default: 'xml')
- `$item`: Default name for numerically indexed items (default: 'item')
- `$attr`: XML attributes for the root element (string or array)
- `$id`: Attribute name for numeric keys (default: 'id')
- `$cdata`: Whether to wrap string values in CDATA (default: true)
- `$listKey`: Array of keys to format as a flat list
- `$specialBool`: Whether to output boolean values as 'true'/'false' strings (default: false)

```
// With custom root element
$xml = XML::build($array, 'root');

// With attributes
$xml = XML::build($array, 'xml', 'item', ['version' => '1.0', 'encoding' => 'UTF-8']);

// Handling lists with nested objects
$listData = [
    'products' => [
        ['name' => 'Product 1', 'price' => 100],
        ['name' => 'Product 2', 'price' => 200]
    ]
];
$xml = XML::build(
    $listData,
    'root',
    'item',
    '',
    'id',
    true,
    ['products']
);
```

### XML::cdata()

[](#xmlcdata)

Wraps a string in CDATA tags.

```
$cdata = XML::cdata('Special characters & < >');
// Result: ]]>
```

### XML::sanitize()

[](#xmlsanitize)

Removes invalid XML characters from a string.

```
$safeXml = XML::sanitize($potentiallyInvalidXml);
```

Advanced Usage
--------------

[](#advanced-usage)

### Custom Configuration

[](#custom-configuration)

```
// Advanced build options
$xml = XML::build(
    $data,
    $root = 'customRoot',
    $item = 'customItem',
    $attr = ['version' => '2.0'],
    $id = 'identifier',
    $cdata = false,
    $listKey = ['products', 'categories'],
    $specialBool = true
);
```

### Performance Optimization

[](#performance-optimization)

```
// For large datasets, disable CDATA if not needed
$xml = XML::build($largeArray, 'root', 'item', '', 'id', false);

// Pre-sanitize XML for better performance
$cleanXml = XML::sanitize($rawXmlString);
$array = XML::parse($cleanXml);
```

Example Use Cases
-----------------

[](#example-use-cases)

### Working with API Responses

[](#working-with-api-responses)

```
// Parse an XML API response
$xmlResponse = getAPIResponse(); // Returns XML string
$data = XML::parse($xmlResponse);

// Process the data as a PHP array
$processedData = processData($data);

// Convert back to XML if needed
$xmlOut = XML::build($processedData);
```

### Handling Complex Structures

[](#handling-complex-structures)

```
$data = [
    'header' => [
        'version' => '1.0',
        'encoding' => 'UTF-8'
    ],
    'body' => [
        'user' => [
            'name' => 'Jane Smith',
            'email' => 'jane@example.com',
            'roles' => [
                'role' => ['admin', 'editor']
            ]
        ],
        'status' => true
    ]
];

$xml = XML::build($data, 'message', 'item', '', 'id', true, [], true);
```

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

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Testing
-------

[](#testing)

```
./vendor/bin/phpunit packages/xml-helper/tests
```

License
-------

[](#license)

This package is open-sourced software licensed under the MIT license. See the [LICENSE](LICENSE) file for more information.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance62

Regular maintenance activity

Popularity16

Limited adoption so far

Community12

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

Unknown

Total

1

Last Release

414d ago

### Community

Maintainers

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

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (1 commits)")

### Embed Badge

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

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

###  Alternatives

[mtdowling/jmespath.php

Declaratively specify how to extract elements from a JSON document

2.0k472.8M135](/packages/mtdowling-jmespathphp)[opis/closure

A library that can be used to serialize closures (anonymous functions) and arbitrary data.

2.6k230.0M284](/packages/opis-closure)[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M229](/packages/masterminds-html5)[sabberworm/php-css-parser

Parser for CSS Files written in PHP

1.8k191.2M65](/packages/sabberworm-php-css-parser)[michelf/php-markdown

PHP Markdown

3.5k52.4M345](/packages/michelf-php-markdown)[jms/metadata

Class/method/property metadata management in PHP

1.8k152.8M88](/packages/jms-metadata)

PHPackages © 2026

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