Skip to content

Heribertosgp/Xml

 
 

Repository files navigation

Fwk\Xml (Parsing and Validation for XML)

Scrutinizer Code Quality Build Status Code Coverage Latest Stable Version Total Downloads Latest Unstable Version License

PHP utility to Parse and Validate XML files.

Installation

Via Composer:

{
    "require": {
        "fwk/xml": "dev-master",
    }
}

If you don't use Composer, you can still download this repository and add it to your include_path PSR-0 compatible

Documentation

Parse a XML file

The classes Fwk\Xml\Map and Fwk\Xml\Path helps you define a parsing map to transform a XML file to a PHP array. Example XML file:

<?xml version="1.0" encoding="UTF-8"?>
<test>
    <properties>
        <property name="test">test_value</property>
        <property name="test2">test_value2</property>
    </properties>
    
    <description>test description</description>
    
    <test-default />
</test>

We want to transform (i.e. parse) this file to obtain its data so we just have to create a Map:

use Fwk\Xml\Map;
use Fwk\Xml\Path;

$map = new Map();

// this path will fetch the <description /> tag
$map->add(Path::factory('/test/description', 'description'));

// this path will fetch all the properties (loop) within the <properties /> tag
$map->add(
    Path::factory('/test/properties/property', 'properties')
    ->loop(true)
    ->attribute('name')
    ->value('value')
);

Now we can execute the Map and exploit the results:

$results = $map->execute(new XmlFile('test.xml'));

var_dump($results);
// [
//      description: "test description", 
//      properties: [
//            (
//                name: "test", 
//                value: "test_value"
//            ),
//            (
//                name: "test2", 
//                value: "test_value2"
//            )
//      ]
// ]

A more complex example can be found here (RSS feed)

Loop with a keyed attribute

Sometimes, XML elements we loop throught are identified by an attribute (ex: <item id="42" />). We can tell our path to use this attribute as the array key!

// the loop() key attribute is an Xpath so any valid Xpath is allowed 
// (@ = attribute of the current element)
$map->add(
    Path::factory('/test/properties/property', 'properties')
    ->loop(true, $key = '@name')
    ->value('value')
);

/* [...] */

var_dump($results);
// [
//      description: "test description", 
//      properties[test]: "test_value",
//      properties[test2]: "test_value2"
// ]

Contributions / Community

Legal

Fwk is licensed under the 3-clauses BSD license. Please read LICENSE for full details.

About

XML Parsing and Validation Utility

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • PHP 100.0%