Search by

byjg / anydataset-xml

byjg

XML abstraction dataset for the AnyDataset library. AnyDataset is an agnostic data source abstraction layer in PHP.

Package info

github.com/byjg/php-anydataset-xml

pkg:composer/byjg/anydataset-xml

Statistics

Installs: 8 956

Dependents: 1

Suggesters: 0

Stars: 2

Open Issues: 0

6.0.0 2025-11-24 18:05 UTC

This package is auto-updated.

Last update: 2026-10-25 23:50:28 UTC


README

sidebar_key anydataset-xml
sidebar_category data-access
tags
php anydataset text-manipulation

AnyDataset-Xml

Read an XML document as a table: choose the node that is a row, map each field with XPath, iterate the rows.

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

Why

Reading XML with DOM or SimpleXML means walking nodes, handling namespaces and repeated elements, and converting every value by hand, each time with different code.

XmlDataset turns it into rows. Say which node is a row and map each field with an XPath expression (or a closure), namespaces included:

$dataset = new XmlDataset($xml, 'book', [
    'category' => '@category',
    'title'    => 'title',
    'lang'     => 'title/@lang',
]);

The result is the same iterator of rows as every other AnyDataset source, so the code that reads it does not care that the data was XML.

Features

  • Simple XML Processing: Process XML data with a clean, consistent API
  • XPath Support: Use XPath expressions to select nodes and attributes
  • Namespace Support: Full support for XML namespaces
  • Repeated Node Handling: Automatically handles repeated nodes by returning arrays
  • Custom Field Processing: Define custom field mappings with closures/callbacks
  • Flexible Input: Accept XML as string, DOMDocument, XmlNode, or File object
  • AnyDataset Integration: Compatible with the AnyDataset abstraction layer

Documentation

Quick Example

<?php
$xml = file_get_contents('example.xml');

$dataset = new \ByJG\AnyDataset\Xml\XmlDataset(
    $xml,        // The XML string, can also be an XmlNode, DOMDocument, or File object
    "book",      // The node that represents a row
    [
        "category" => "@category",
        "title" => "title",
        "lang" => "title/@lang",
        "lang2" => function ($row) {
            return substr($row->get('lang'), 0, 2);
        }
    ] // Mapping columns
);

$iterator = $dataset->getIterator();
foreach ($iterator as $row) {
    echo $row->get('category'); // Print COOKING, CHILDREN, WEB
    echo $row->get('title');    // Print Everyday Italian, Harry Potter, Learning XML
    echo $row->get('lang');     // Print en-US, de-DE, pt-BR
    echo $row->get('lang2');    // Print en, de, pt
}

Installation

composer require "byjg/anydataset-xml"

Running Tests

vendor/bin/phpunit

Open source ByJG