kiwilan / php-xml-reader
PHP package to read XML with nice API.
Fund package maintenance!
kiwilan
Installs: 8 274
Dependents: 4
Suggesters: 0
Security: 0
Stars: 5
Watchers: 1
Forks: 1
Open Issues: 0
Requires
- php: ^8.0
Requires (Dev)
- laravel/pint: ^1.2
- pestphp/pest: ^1.20
- phpstan/phpstan: ^1.10
- spatie/ray: ^1.28
README
PHP package to read XML with nice API, heavily inspired by stackoverflow answer
.
About
PHP have native functions to read XML files with SimpleXML
, but it's not easy to use and not very flexible. This package offer to read XML files as array, with a simple and flexible API.
Requirements
- PHP version >= 8.0
Installation
You can install the package via composer:
composer require kiwilan/php-xml-reader
Usage
You can read XML from path or from content.
mapContent
:boolean
If a key has only@content
key, return only the value of@content
. Default:true
.failOnError
:boolean
Throw exception if XML is invalid. Default:true
.
use KiwiLan\XmlReader\XmlReader; $xml = XmlReader::make('path/to/file.xml', bool $mapContent = true, bool $failOnError = true);
Methods
Advanced methods
Basic usage
XML as multidimensional array from root
(safe).
$content = $xml->getContents();
Basic usage.
$title = $content['metadata']['dc:title'] ?? null;
Find
Find key will return first value where key that contain title
(safe).
$title = $xml->find('title', strict: false);
Find key will return first value where key is dc:title
(safe)
$dcTitle = $xml->find('dc:title');
Find key will return first value where key that contain dc:title
and return @content
(safe)
$dcCreator = $xml->find('dc:creator', content: true);
Find key will return first value where key contain dc:creator
and return @attributes
(safe)
$dcCreator = $xml->find('dc:creator', attributes: true);
Search
Search will return all values that contain dc
(safe)
$dc = $xml->search('dc');
Extract
Extract metadata
key, if not found return null (safe)
$rootKey = $xml->extract('metadata');
Extract metadata
and dc:title
keys (safe)
$subSubKey = $xml->extract(['metadata', 'dc:title']);
Get content
If you want to extract only @content
you could use parseContent()
method, if you want to extract only @attributes
you could use parseAttributes()
method.
Extract dc:title
key and return @content
(safe)
$title = $xml->extract(['metadata', 'dc:title']); $title = XmlReader::parseContent($title);
Extract dc:creator
key and return @content
(safe)
$creator = $xml->extract(['metadata', 'dc:creator']); $creator = XmlReader::parseContent($creator);
Extract dc:creator
key and return @attributes
(safe)
$creatorAttributes = $xml->extract(['metadata', 'dc:creator']); $creatorAttributes = XmlReader::parseAttributes($creatorAttributes);
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Credits
spatie
forspatie/package-skeleton-php
License
The MIT License (MIT). Please see License File for more information.