ottosmops/xmltoolkit

Add and remove XML tags and attributes.

v1.0.0 2025-03-19 14:23 UTC

This package is auto-updated.

Last update: 2025-03-19 14:25:53 UTC


README

Build Status License Total Downloads

Xmltoolkit is a PHP class that provides various utilities for manipulating XML documents. It allows loading XML from files or strings, performing XPath queries, and modifying XML elements and attributes.

Installation

Use Composer to install the package:

composer require ottosmops/xmltoolkit

Usage

<?php
require 'vendor/autoload.php';

use Ottosmops\Xmltoolkit;

$xml = new Xmltoolkit();
$xml->loadFromFile('example.xml');
$xml->renameTagByXPath('//a', 'ref');
$xml->saveToFile('example.xml');

Methods

Load an XML file into the DOM object and ensure it is UTF-8 encoded.

public function loadFromFile(string $filePath): bool

Load an XML string into the DOM object and ensure it is UTF-8 encoded.

public function loadFromString(string $xmlString): bool

Load an XML/HTML Fragment

public function loadFromFragment(string $xmlFragment): bool

Save the XML document to a file and ensure it is UTF-8 encoded.

public function saveToFile(string $filePath): bool

Returns the XML as a string and ensures it is UTF-8 encoded.

public function saveToString(): string

Rename a tag found by an XPath expression.

public function renameTagByXPath(string $xpathExpression, string $newTagName): 
void

Rename an attribute found by an XPath expression.

public function renameAttributeByXPath(string $xpathExpression, string $oldAttributeName, string $newAttributeName): void

Add a new attribute to a tag found by an XPath expression.

public function addAttributeByXPath(string $xpathExpression, string $attributeName, string $attributeValue): void

Remove an attribute from a tag found by an XPath expression.

public function removeAttributeByXPath(string $xpathExpression, string $attributeName): void

Does an arbitrary XPath query and returns the found nodes as an array.

public function queryXPath(string $xpathExpression): array

Inserts an HTML string after the nodes found by an XPath expression.

public function appendHtmlToXPath(string $xpathExpression, string $htmlString): void

Removes an element found by an XPath expression.

    public function removeElementByXPath(string $xpathExpression): void

Wrap an element found by an XPath expression with a new element.

public function wrapElementByXPath(string $xpathExpression, string $wrapperTagName): void

Remove an element but keep its content (unwrap the element) based on an XPath expression.

public function unwrapElementByXPath(string $xpathExpression): void

Tests

Run the tests with PHPUnit:

vendor/bin/phpunit