rufov/converter-array-xml

The class is designed to convert an XML document into a PHP array and vice versa

1.0.0 2023-02-27 00:00 UTC

README

Software License

The class is designed to convert an XML document into a PHP array and vice versa

Installation

The package could be installed with composer:

composer require rufov/converter-array-xml

Usage

use RufovS\ConverterArrayXML\ConverterArrayXML;

$xml = <<<_XML
<?xml version="1.0"?>
<root xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <GoodGuy attr1="value">
        <name><![CDATA[<h1>Luke Skywalker</h1>]]></name>
        <weapon>Lightsaber</weapon>
    </GoodGuy>
    <BadGuy>
        <name>Sauron</name>
        <weapon>Evil Eye</weapon>
    </BadGuy>
</root>
_XML;

$result = ConverterArrayXML::xmlToArr($xml);

After running this piece of code $result will contain:

$result = [
    'root' => [
        '_attributes' => [
                'xmlns:xs=' => 'http://www.w3.org/2001/XMLSchema',
                'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance'
        ],
        'GoodGuy' => [
             '_attributes' => [
                'attr1' => 'value'
            ],
            'name' => [
                '_cdata' => '<h1>Luke Skywalker</h1>'
            ],
            'weapon' => 'Lightsaber'
        ],
        'BadGuy' => [
            'name' => 'Sauron',
            'weapon' => 'Evil Eye'
        ]
    ]
];

You can also convert an array to xml. This is done as follows:

use RufovS\ConverterArrayXML\ConverterArrayXML;

$array = [
    'root' => [
        '_attributes' => [
                'xmlns:xs=' => 'http://www.w3.org/2001/XMLSchema',
                'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance'
        ],
        'GoodGuy' => [
             '_attributes' => [
                'attr1' => 'value'
            ],
            'name' => [
                '_cdata' => '<h1>Luke Skywalker</h1>'
            ],
            'weapon' => 'Lightsaber'
        ],
        'BadGuy' => [
            'name' => 'Sauron',
            'weapon' => 'Evil Eye'
        ]
    ]
];

$result = ConverterArrayXML::arrayToXml($array);

At the end you will get the following xml document.

<?xml version="1.0"?>
<root xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <GoodGuy attr1="value">
        <name><![CDATA[<h1>Luke Skywalker</h1>]]></name>
        <weapon>Lightsaber</weapon>
    </GoodGuy>
    <BadGuy>
        <name>Sauron</name>
        <weapon>Evil Eye</weapon>
    </BadGuy>
</root>

Testing

vendor/bin/phpunit

Contributors

Thanks to all the people who already contributed!

Contributors

Changelog

Please see CHANGELOG for more information on what has changed recently.

License

The BSD-3-Clause license. Please see License File for more information.