Skip to main content

XML Utility

Build, query and convert XML without fighting DOM: a fluent API, XPath with namespaces, and PHP models mapped to XML with attributes.

Sponsor Build Status Opensource ByJG Install MCP Server GitHub source GitHub license GitHub release

Why​

PHP's DOM is complete but verbose: creating a node, adding a namespace or running an XPath query takes several objects and many lines, and turning a PHP object into XML is left to you.

XML Util wraps it in a small API, and maps a model to XML from attributes on the class:

#[XmlEntity(rootElementName: 'Person')]
class Person
{
#[XmlProperty(elementName: 'Name')]
public string $name;
}

echo (new EntityParser())->parse($person)->toString(format: true);
  • Fluent building and XPath (appendChild(), selectNodes()), with namespaces.
  • Models to XML by attributes, instead of hand-written serialization.
  • XML to arrays with the same rules as byjg/serializer (toFullArray()).

Overview​

PHP XML Util provides a comprehensive set of tools for XML manipulation in PHP applications. It simplifies common XML operations with an intuitive API, allowing developers to create, modify, query, and validate XML documents with minimal code.

The library is designed to be lightweight yet powerful, offering features that go beyond PHP's built-in XML functionality while maintaining a clean and easy-to-use interface.

Key Features​

  • Simple XML Creation API - Create and manipulate XML documents programmatically with an intuitive API
  • XPath Querying - Easily query and navigate XML documents using XPath expressions
  • PHP Model ↔ XML Conversion - Seamlessly convert between PHP objects and XML representations
  • Attribute-Based Mapping - Use PHP attributes to control XML serialization behavior
  • Namespace Support - Full support for XML namespaces in all operations
  • Document Cleaning - Selectively remove specific tags from XML documents
  • XML Validation - Validate XML documents against schemas
  • File Handling - Convenient methods for loading and saving XML from/to files

Quick Example​

<?php
use ByJG\XmlUtil\XmlDocument;

// Create a new XML document
$xml = new XmlDocument('<root />');

// Build the document structure
$myNode = $xml->appendChild('mynode');
$myNode->appendChild('subnode', 'text');
$myNode->appendChild('subnode', 'more text');
$otherNode = $myNode->appendChild('othersubnode', 'other text');
$otherNode->addAttribute('attr', 'value');

// Output formatted XML
echo $xml->toString(format: true);

Output:

<?xml version="1.0" encoding="utf-8"?>
<root>
<mynode>
<subnode>text</subnode>
<subnode>more text</subnode>
<othersubnode attr="value">other text</othersubnode>
</mynode>
</root>

Documentation​

The library is fully documented with detailed guides and examples for each feature:

Installation​

composer require "byjg/xmlutil"

Running Tests​

vendor/bin/phpunit

Open source ByJG