PHPackages                             atk14/xmole - 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. atk14/xmole

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

atk14/xmole
===========

Simple XML parser with path-based access to elements, attributes and subtrees

v1.0.4(1mo ago)023.8k↓25%4MITPHPPHP &gt;=5.6.0CI passing

Since Jul 10Pushed 4w ago1 watchersCompare

[ Source](https://github.com/atk14/XMole)[ Packagist](https://packagist.org/packages/atk14/xmole)[ Docs](https://github.com/atk14/XMole)[ RSS](/packages/atk14-xmole/feed)WikiDiscussions master Synced yesterday

READMEChangelogDependencies (6)Versions (6)Used By (4)

XMole
=====

[](#xmole)

[![Tests](https://github.com/atk14/XMole/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/atk14/XMole/actions/workflows/tests.yml)

XMole is a simple PHP XML parser that turns XML into a traversable object tree. It wraps PHP's built-in expat parser and adds a convenient path-based API for reading element data, attributes, and subtrees.

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

[](#installation)

```
composer require atk14/xmole
```

Basic usage
-----------

[](#basic-usage)

Pass XML directly to the constructor, or call `parse()` separately:

```
$xm = new XMole('

    John Doe
    Widget
    Gadget

');

$xm->get_data("customer");            // "John Doe"
$xm->get_attribute("order", "id");    // "42"
$xm->get_root_name();                 // "order"
```

Path syntax
-----------

[](#path-syntax)

Paths work similarly to XPath but use a simpler `/`-separated format.

```
// Absolute path — must match from the root
$xm->get_data("/order/customer");

// Relative path — matches anywhere in the tree
$xm->get_data("customer");

// Root element shorthand
$xm->get_data("/");           // data of the root element
$xm->get_attributes();        // attributes of the root element
$xm->get_attribute("id");     // attribute of the root element (path can be omitted)
```

Trailing slashes are ignored: `"order/"` and `"order"` are equivalent.

Reading data and attributes
---------------------------

[](#reading-data-and-attributes)

```
// Element text content
$xm->get_data("customer");                    // "John Doe"

// Single attribute
$xm->get_attribute("order", "status");        // "pending"
$xm->get_attribute("status");                 // same — root element attribute shorthand

// All attributes as an associative array
$xm->get_attributes("order");                 // ["id" => "42", "status" => "pending"]
$xm->get_root_attributes();                   // same for the root element

// Returns null when the element or attribute is not found
$xm->get_data("nonexistent");                 // null
$xm->get_attribute("order", "nonexistent");   // null
```

Whitespace at the beginning and end of element data is trimmed by default. To disable trimming:

```
$xm = new XMole($xml, ["trim_data" => false]);
// or
$xm->set_trim_data(false);
```

Navigating subtrees
-------------------

[](#navigating-subtrees)

Use `get_xmole()` to get a subtree as a new XMole instance:

```
$item = $xm->get_xmole("item");       // first matching
$item->get_data();                    // "Widget"  (root element data)
$item->get_attribute("sku");          // "ABC"
```

Use `get_xmoles()` to get all matching elements:

```
$items = $xm->get_xmoles("item");     // array of XMole instances

$items[0]->get_data();                // "Widget"
$items[1]->get_data();                // "Gadget"
```

Iterating over children
-----------------------

[](#iterating-over-children)

```
// Access children by index
$first  = $xm->get_child(0);
$second = $xm->get_child(1);

// Get all direct children at once
$children = $xm->get_children();
foreach ($children as $child) {
    echo $child->get_root_name() . ": " . $child->get_data() . "\n";
}

// Iterate sequentially with get_next_child()
while ($child = $xm->get_next_child()) {
    echo $child->get_attribute("sku") . "\n";
}

// Reset the internal pointer to start over
$xm->reset_next_child_index();
```

Error handling
--------------

[](#error-handling)

`parse()` returns `false` on failure. Error details are available via `get_error_message()` or the optional reference parameters:

```
$xm = new XMole();
if (!$xm->parse($xml, $err_code, $err_message)) {
    echo $err_message;  // e.g. "XML parser error (76): Mismatched tag on line 3"
}
```

`error()` returns `true` if the last parse failed:

```
$xm = new XMole($possibly_invalid_xml);
if ($xm->error()) {
    echo $xm->get_error_message();
}
```

Encoding conversion
-------------------

[](#encoding-conversion)

XMole can transparently convert character encoding while parsing, using the [atk14/translate](https://github.com/atk14/Translate) library. Input encoding is auto-detected from the XML declaration if not set explicitly.

```
$xm = new XMole();
$xm->set_input_encoding("UTF-8");
$xm->set_output_encoding("WINDOWS-1250");
$xm->parse($xml);
```

Set both at once with `set_encoding()`:

```
$xm->set_encoding("ISO-8859-2");
```

Comparing XML
-------------

[](#comparing-xml)

`is_same_like()` and the static `AreSame()` compare two XML documents structurally. Attribute order is ignored.

```
$xml1 = '';
$xml2 = '';   // same attributes, different order

XMole::AreSame($xml1, $xml2);           // true

$xm = new XMole($xml1);
$xm->is_same_like($xml2);               // true
$xm->is_same_like('');   // false

// Returns null if either document is invalid
XMole::AreSame($xml1, '');         // null
```

Building XML safely
-------------------

[](#building-xml-safely)

Two static helpers encode values for safe embedding in XML:

```
// For text content
$xml = "" . XMole::ToXML($user_input) . "";

// For attribute values
$xml = '';
```

`ToXML()` encodes `& < > " '` and strips control characters invalid in XML 1.0. `ToAttribsValue()` encodes the same characters and also converts newlines to spaces.

Testing
-------

[](#testing)

```
composer install
cd test && ../vendor/bin/run_unit_tests
```

License
-------

[](#license)

XMole is free software distributed [under the terms of the MIT license](http://www.opensource.org/licenses/mit-license).

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance92

Actively maintained with recent releases

Popularity26

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

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

Total

5

Last Release

58d ago

PHP version history (2 changes)v1.0PHP &gt;=5.3.0

v1.0.1PHP &gt;=5.6.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/974278?v=4)[Jaromir Tomek](/maintainers/yarri)[@yarri](https://github.com/yarri)

---

Top Contributors

[![yarri](https://avatars.githubusercontent.com/u/974278?v=4)](https://github.com/yarri "yarri (37 commits)")

---

Tags

xmlparseratk14

### Embed Badge

![Health badge](/badges/atk14-xmole/health.svg)

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

###  Alternatives

[masterminds/html5

An HTML5 parser and serializer.

1.8k269.7M321](/packages/masterminds-html5)[imangazaliev/didom

Simple and fast HTML parser

2.2k2.5M72](/packages/imangazaliev-didom)[orchestra/parser

XML Document Parser for Laravel and PHP

4671.8M7](/packages/orchestra-parser)[laravie/parser

XML Document Parser for PHP

2302.1M8](/packages/laravie-parser)[goetas-webservices/xsd-reader

Read any XML Schema (XSD) programmatically with PHP

625.2M22](/packages/goetas-webservices-xsd-reader)[vipnytt/sitemapparser

XML Sitemap parser class compliant with the Sitemaps.org protocol.

832.3M10](/packages/vipnytt-sitemapparser)

PHPackages © 2026

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