decodelabs/exemplar

Powerful XML tools

v0.4.2 2024-08-21 23:11 UTC

This package is auto-updated.

Last update: 2024-11-04 21:35:58 UTC


README

PHP from Packagist Latest Version Total Downloads GitHub Workflow Status PHPStan License

Powerful XML tools for PHP.

Exemplar provides a set of exhaustive and intuitive interfaces for reading, writing and manipulating XML documents and fragments.

Get news and updates on the DecodeLabs blog.

Installation

composer require decodelabs/exemplar

Usage

Reading & manipulating

Access and manipulate XML files with a consolidated interface wrapping the DOM functionality available in PHP:

use DecodeLabs\Exemplar\Element as XmlElement;

$element = XmlElement::fromFile('/path/to/my/file.xml');

if($element->hasAttribute('old')) {
    $element->removeAttribute('old');
}

$element->setAttribute('new', 'value');

foreach($element->scanChildrenOfType('section') as $sectTag) {
    $inner = $sectTag->getFirstChildOfType('title');
    $sectTag->removeChild($inner);

    // Flatten to plain text
    echo $sectTag->getComposedTextContent();
}

file_put_contents('newfile.xml', (string)$element);

See Element.php for the full interface.

Writing

Programatically generate XML output with a full-featured wrapper around PHP's XML Writer:

use DecodeLabs\Exemplar\Writer as XmlWriter;

$writer = new XmlWriter();
$writer->writeHeader();

$writer->{'ns:section[ns:attr1=value].test'}(function ($writer) {
    $writer->{'title#main'}('This is a title');

    $writer->{'@body'}('This is an element with content wrapped in CDATA tags.');
    $writer->writeCData('This is plain CDATA');
});

echo $writer;

This creates:

<?xml version="1.0" encoding="UTF-8"?>
<ns:section ns:attr1="value" class="test">
    <title id="main">This is a title</title>
    <body><![CDATA[This is an element with content wrapped in CDATA tags.]]></body>
<![CDATA[This is plain CDATA]]></ns:section>

See Writer.php for the full interface.

Licensing

Exemplar is licensed under the MIT License. See LICENSE for the full license text.