xaamin / xml-to-array
XML to array parser using namespaces
Requires
- php: >=8.1
- ext-dom: *
Requires (Dev)
- pestphp/pest: ^5.3
- phpstan/phpstan: ^2.1
- squizlabs/php_codesniffer: ^3.8
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Converts XML documents into PHP arrays. Namespace prefixes are removed, attributes become array keys and repeated nodes become lists. Nodes that may repeat (e.g. invoice lines) can be declared as unbounded so they are always returned as a list, even when the document contains a single one. Those rules can be written by hand, loaded from JSON or generated from the document XSD schemas.
Requirements
- PHP 8.1 or higher
ext-dom
Installation
composer require xaamin/xml-to-array
Usage
XmlParser::make() (or load()) accepts an XML string, a file path or a DOMDocument.
use Xaamin\XmlToArray\XmlParser;
$xml = <<<'XML'
<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/4" Version="4.0" Total="100.00">
<cfdi:Emisor Rfc="AAA010101AAA" Nombre="Emisor SA"/>
<cfdi:Conceptos>
<cfdi:Concepto Cantidad="1" Descripcion="Uno"/>
<cfdi:Concepto Cantidad="2" Descripcion="Dos"/>
</cfdi:Conceptos>
<cfdi:Complemento/>
</cfdi:Comprobante>
XML;
$data = XmlParser::make($xml)->toArray();
// [
// 'Version' => '4.0',
// 'Total' => '100.00',
// 'Emisor' => ['Rfc' => 'AAA010101AAA', 'Nombre' => 'Emisor SA'],
// 'Conceptos' => [
// 'Concepto' => [
// ['Cantidad' => '1', 'Descripcion' => 'Uno'],
// ['Cantidad' => '2', 'Descripcion' => 'Dos'],
// ],
// ],
// 'Complemento' => '',
// ]
The root element is not included in the output, its attributes and children are the top level keys.
Text nodes
Text-only nodes are collapsed into values. Repeated ones become a list, and when they have a single attribute its value is used as key:
XmlParser::make(<<<'XML'
<Root>
<Name> Jane Doe </Name>
<Phone>555-0001</Phone>
<Phone>555-0002</Phone>
<Label lang="es">Hola</Label>
<Label lang="en">Hello</Label>
</Root>
XML)->toArray();
// [
// 'Name' => 'Jane Doe',
// 'Phone' => ['555-0001', '555-0002'],
// 'Label' => ['es' => 'Hola', 'en' => 'Hello'],
// ]
Reading values with dot notation
get() returns the same values as toArray(). Use numeric segments to select an item of a list.
$parser = XmlParser::make($xml);
$parser->get('Version'); // '4.0'
$parser->get('Emisor.Rfc'); // 'AAA010101AAA'
$parser->get('Conceptos.Concepto.1.Descripcion'); // 'Dos'
$parser->get('Emisor.Missing', 'default'); // 'default'
$parser->get(); // the whole array
Reusing the parser
$parser = new XmlParser();
$first = $parser->load($firstXml)->toArray();
$second = $parser->load('/path/to/second.xml')->toArray();
Unbounded nodes
Without rules, a node that appears only once is returned as an array instead of a list, so the shape of the output depends on the document:
XmlParser::make('<Root><Items><Item Sku="A"/></Items></Root>')->toArray();
// ['Items' => ['Item' => ['Sku' => 'A']]]
Declare the node path (from the root element, without prefixes) as unbounded to always get a list:
use Xaamin\XmlToArray\Support\UnboundedNodes;
XmlParser::make('<Root><Items><Item Sku="A"/></Items></Root>')
->withUnboundedNodes(new UnboundedNodes(['Root > Items > Item']))
->toArray();
// ['Items' => ['Item' => [['Sku' => 'A']]]]
Only the exact paths are affected. The default separator is ' > '; a custom one can be given as the second argument, and leading path segments can be ignored:
new UnboundedNodes(['Root/Items/Item'], '/');
(new UnboundedNodes(['Items > Item']))->ignore(['Root']);
From JSON
A JSON file (or raw JSON string) with a list of paths:
[
"Invoice > Items > Item",
"Invoice > Items > Item > Tax"
]
use Xaamin\XmlToArray\Support\UnboundedNodesFromJsonFile;
$unbounded = (new UnboundedNodesFromJsonFile('/path/to/unbounded.json'))->make();
$data = XmlParser::make($xml)->withUnboundedNodes($unbounded)->toArray();
Invalid content throws a JsonException or LogicException.
From an XSD
UnboundedNodesFromXsd reads an XSD (local path or URL) and collects every element whose minOccurs/maxOccurs is greater than 1 or unbounded, including elements inside repeatable sequence and choice groups.
use Xaamin\XmlToArray\Support\UnboundedNodesFromXsd;
$unbounded = (new UnboundedNodesFromXsd())->make('/path/to/invoice.xsd');
$unbounded->getData();
// ['Invoice > Items > Item', 'Invoice > Items > Item > Tax', ...]
From the document schemas
UnboundedNodesFromSchemas reads every xsi:schemaLocation declared in the XML and merges the rules of all the referenced XSD files:
use Xaamin\XmlToArray\Support\UnboundedNodesFromSchemas;
$unbounded = (new UnboundedNodesFromSchemas())->make($xml);
$data = XmlParser::make($xml)->withUnboundedNodes($unbounded)->toArray();
Caching and local schemas
Remote XSD files are downloaded once and stored in the cache path. To avoid network access, place copies of the schemas in an assets path following the host/path of their URL, e.g. http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd is looked up at {assets}/www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd. Both paths default to the system temp directory.
Enable cacheUnboundedNodes to also store the computed rules as JSON; the cache is invalidated when the XSD contents change.
$factory = new UnboundedNodesFromXsd(
'/var/cache/xsd', // cache path
'/srv/app/resources/xsd', // assets path
['cacheUnboundedNodes' => true]
);
$unbounded = (new UnboundedNodesFromSchemas($factory))->make($xml);
// Or let the schemas factory build the default one
$schemas = new UnboundedNodesFromSchemas(null, ['cacheUnboundedNodes' => true]);
$schemas->setCachePath('/var/cache/xsd')->setAssetsPath('/srv/app/resources/xsd');
Working with the node tree
parse() returns the root Xaamin\XmlToArray\Support\Node for lower level access:
$root = XmlParser::make($xml)->parse();
$root->getName(); // 'Comprobante'
$root->getAttributes(); // ['Version' => '4.0', 'Total' => '100.00']
foreach ($root->getChildren()->all() as $child) {
$child->getName(); // 'Emisor', 'Conceptos', ...
$child->getTag(); // 'Comprobante > Emisor', ...
}
Testing
composer test
License
The MIT License (MIT). Please see License File for more information.