All Projects → spatie → Array To Xml

spatie / Array To Xml

Licence: mit
A simple class to convert an array to xml

Projects that are alternatives of or similar to Array To Xml

Ohloh api
Ohloh API examples
Stars: ✭ 64 (-91.4%)
Mutual labels:  api, xml
Jmapper Core
Elegance, high performance and robustness all in one java bean mapper
Stars: ✭ 159 (-78.63%)
Mutual labels:  api, xml
Countries States Cities Database
🌍 World countries, states, regions, provinces, cities, towns in JSON, SQL, XML, PLIST, YAML, and CSV. All Countries, States, Cities with ISO2, ISO3, Country Code, Phone Code, Capital, Native Language, Timezones, Latitude, Longitude, Region, Subregion, Flag Emoji, and Currency. #countries #states #cities
Stars: ✭ 1,130 (+51.88%)
Mutual labels:  api, xml
Pgo
Go library for PHP community with convenient functions
Stars: ✭ 51 (-93.15%)
Mutual labels:  api, array
SNAP
Easy data format saving and loading for GameMaker Studio 2.3.2
Stars: ✭ 49 (-93.41%)
Mutual labels:  xml, array
Response Xml
The missing XML support for Laravel's Response class.
Stars: ✭ 56 (-92.47%)
Mutual labels:  api, xml
Scobot
SCORM API for Content. JavaScript library, QUnit tests and examples.
Stars: ✭ 128 (-82.8%)
Mutual labels:  api, xml
Configurate
A simple configuration library for Java applications providing a node structure, a variety of formats, and tools for transformation
Stars: ✭ 148 (-80.11%)
Mutual labels:  xml, configuration
utils.js
👷 🔧 zero dependencies vanilla JavaScript utils.
Stars: ✭ 14 (-98.12%)
Mutual labels:  xml, array
Horaires Ratp Api
Webservice pour les horaires et trafic RATP en temps réel
Stars: ✭ 232 (-68.82%)
Mutual labels:  api, xml
Swift Utils
A collection of handy swift utils
Stars: ✭ 253 (-65.99%)
Mutual labels:  array, xml
Dog Ceo Api
The API hosted at dog.ceo
Stars: ✭ 393 (-47.18%)
Mutual labels:  api, xml
Uxdm
🔀 UXDM helps developers migrate data from one system or format to another.
Stars: ✭ 159 (-78.63%)
Mutual labels:  array, xml
Ins sandstorm
[INS] Config setting for our sandstorm server
Stars: ✭ 61 (-91.8%)
Mutual labels:  api, configuration
Konf
A type-safe cascading configuration library for Kotlin/Java/Android, supporting most configuration formats
Stars: ✭ 225 (-69.76%)
Mutual labels:  xml, configuration
Jokeapi
A REST API that serves uniformly and well formatted jokes in JSON, XML, YAML or plain text format that also offers a great variety of filtering methods
Stars: ✭ 71 (-90.46%)
Mutual labels:  api, xml
Dasel
Query, update and convert data structures from the command line. Comparable to jq/yq but supports JSON, TOML, YAML, XML and CSV with zero runtime dependencies.
Stars: ✭ 759 (+2.02%)
Mutual labels:  xml, configuration
Drago
A flexible configuration manager for Wireguard networks
Stars: ✭ 204 (-72.58%)
Mutual labels:  api, configuration
Php Curl Class
PHP Curl Class makes it easy to send HTTP requests and integrate with web APIs
Stars: ✭ 2,903 (+290.19%)
Mutual labels:  api, xml
Poco
The POCO C++ Libraries are powerful cross-platform C++ libraries for building network- and internet-based applications that run on desktop, server, mobile, IoT, and embedded systems.
Stars: ✭ 5,762 (+674.46%)
Mutual labels:  xml, configuration

Convert an array to xml

Latest Version Software License Tests Total Downloads

This package provides a very simple class to convert an array to an xml string.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Install

You can install this package via composer.

composer require spatie/array-to-xml

Usage

use Spatie\ArrayToXml\ArrayToXml;
...
$array = [
    'Good guy' => [
        'name' => 'Luke Skywalker',
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => 'Sauron',
        'weapon' => 'Evil Eye'
    ]
];

$result = ArrayToXml::convert($array);

After running this piece of code $result will contain:

<?xml version="1.0"?>
<root>
    <Good_guy>
        <name>Luke Skywalker</name>
        <weapon>Lightsaber</weapon>
    </Good_guy>
    <Bad_guy>
        <name>Sauron</name>
        <weapon>Evil Eye</weapon>
    </Bad_guy>
</root>

Setting the name of the root element

Optionally you can set the name of the rootElement by passing it as the second argument. If you don't specify this argument (or set it to an empty string) "root" will be used.

$result = ArrayToXml::convert($array, 'customrootname');

Handling key names

By default all spaces in the key names of your array will be converted to underscores. If you want to opt out of this behaviour you can set the third argument to false. We'll leave all keynames alone.

$result = ArrayToXml::convert($array, 'customrootname', false);

Adding attributes

You can use a key named _attributes to add attributes to a node, and _value to specify the value.

$array = [
    'Good guy' => [
        '_attributes' => ['attr1' => 'value'],
        'name' => 'Luke Skywalker',
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => 'Sauron',
        'weapon' => 'Evil Eye'
    ],
    'The survivor' => [
        '_attributes' => ['house'=>'Hogwarts'],
        '_value' => 'Harry Potter'
    ]
];

$result = ArrayToXml::convert($array);

This code will result in:

<?xml version="1.0"?>
<root>
    <Good_guy attr1="value">
        <name>Luke Skywalker</name>
        <weapon>Lightsaber</weapon>
    </Good_guy>
    <Bad_guy>
        <name>Sauron</name>
        <weapon>Evil Eye</weapon>
    </Bad_guy>
    <The_survivor house="Hogwarts">
        Harry Potter
    </The_survivor>
</root>

Note, that the value of the _value field must be a string. (More)

Using reserved characters

It is also possible to wrap the value of a node into a CDATA section. This allows you to use reserved characters.

$array = [
    'Good guy' => [
        'name' => [
            '_cdata' => '<h1>Luke Skywalker</h1>'
        ],
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => '<h1>Sauron</h1>',
        'weapon' => 'Evil Eye'
    ]
];

$result = ArrayToXml::convert($array);

This code will result in:

<?xml version="1.0"?>
<root>
    <Good_guy>
        <name><![CDATA[<h1>Luke Skywalker</h1>]]></name>
        <weapon>Lightsaber</weapon>
    </Good_guy>
    <Bad_guy>
        <name>&lt;h1&gt;Sauron&lt;/h1&gt;</name>
        <weapon>Evil Eye</weapon>
    </Bad_guy>
</root>

If your input contains something that cannot be parsed a DOMException will be thrown.

Customize the XML declaration

You could specify specific values in for:

  • encoding as the fourth argument (string)
  • version as the fifth argument (string)
  • standalone as sixth argument (boolean)
$result = ArrayToXml::convert($array, [], true, 'UTF-8', '1.1', [], true);

This will result in:

<?xml version="1.1" encoding="UTF-8" standalone="yes"?>

Adding attributes to the root element

To add attributes to the root element provide an array with an _attributes key as the second argument. The root element name can then be set using the rootElementName key.

$result = ArrayToXml::convert($array, [
    'rootElementName' => 'helloyouluckypeople',
    '_attributes' => [
        'xmlns' => 'https://github.com/spatie/array-to-xml',
    ],
], true, 'UTF-8');

Using a multi-dimensional array

Use a multi-dimensional array to create a collection of elements.

$array = [
    'Good guys' => [
        'Guy' => [
            ['name' => 'Luke Skywalker', 'weapon' => 'Lightsaber'],
            ['name' => 'Captain America', 'weapon' => 'Shield'],
        ],
    ],
    'Bad guys' => [
        'Guy' => [
            ['name' => 'Sauron', 'weapon' => 'Evil Eye'],
            ['name' => 'Darth Vader', 'weapon' => 'Lightsaber'],
        ],
    ],
];

This will result in:

<?xml version="1.0" encoding="UTF-8"?>
<helloyouluckypeople xmlns="https://github.com/spatie/array-to-xml">
    <Good_guys>
        <Guy>
            <name>Luke Skywalker</name>
            <weapon>Lightsaber</weapon>
        </Guy>
        <Guy>
            <name>Captain America</name>
            <weapon>Shield</weapon>
        </Guy>
    </Good_guys>
    <Bad_guys>
        <Guy>
            <name>Sauron</name>
            <weapon>Evil Eye</weapon>
        </Guy>
        <Guy>
            <name>Darth Vader</name>
            <weapon>Lightsaber</weapon>
        </Guy>
    </Bad_guys>
</helloyouluckypeople>

Handling numeric keys

The package can also can handle numeric keys:

$array = [
    100 => [
        'name' => 'Vladimir',
        'nickname' => 'greeflas',
    ],
    200 => [
        'name' => 'Marina',
        'nickname' => 'estacet',
    ],
];

$result = ArrayToXml::convert(['__numeric' => $array]);

This will result in:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <numeric_100>
        <name>Vladimir</name>
        <nickname>greeflas</nickname>
    </numeric_100>
    <numeric_200>
        <name>Marina</name>
        <nickname>estacet</nickname>
    </numeric_200>
</root>

You can change key prefix with setter method called setNumericTagNamePrefix().

Using custom keys

The package can also can handle custom keys:

$array = [
    '__custom:custom-key:1' => [
        'name' => 'Vladimir',
        'nickname' => 'greeflas',
    ],
    '__custom:custom-key:2' => [
        'name' => 'Marina',
        'nickname' => 'estacet',
        'tags' => [
            '__custom:tag:1' => 'first-tag',
            '__custom:tag:2' => 'second-tag',
        ]
    ],
];

$result = ArrayToXml::convert($array);

This will result in:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <custom-key>
        <name>Vladimir</name>
        <nickname>greeflas</nickname>
    </custom-key>
    <custom-key>
        <name>Marina</name>
        <nickname>estacet</nickname>
        <tags>
            <tag>first-tag</tag>
            <tag>second-tag</tag>
        </tags>
    </custom-key>
</root>

A custom key contains three, colon-separated parts: "__custom:[custom-tag]:[unique-string]".

  • "__custom"
    • The key always starts with "__custom".
  • [custom-tag]
    • The string to be rendered as the XML tag.
  • [unique-string]
    • A unique string that avoids overwriting of duplicate keys in PHP arrays.

a colon character can be included within the custom-tag portion by escaping it with a backslash:

$array = [
    '__custom:ns\\:custom-key:1' => [
        'name' => 'Vladimir',
        'nickname' => 'greeflas',
    ],
    '__custom:ns\\:custom-key:2' => [
        'name' => 'Marina',
        'nickname' => 'estacet',
        'tags' => [
            '__custom:ns\\:tag:1' => 'first-tag',
            '__custom:ns\\:tag:2' => 'second-tag',
        ]
    ],
];

This will result in:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <ns:custom-key>
        <name>Vladimir</name>
        <nickname>greeflas</nickname>
    </ns:custom-key>
    <ns:custom-key>
        <name>Marina</name>
        <nickname>estacet</nickname>
        <tags>
            <ns:tag>first-tag</ns:tag>
            <tns:ag>second-tag</tns:ag>
        </tags>
    </ns:custom-key>
</root>

Setting DOMDocument properties

To set properties of the internal DOMDocument object just pass an array consisting of keys and values. For a full list of valid properties consult https://www.php.net/manual/en/class.domdocument.php.

You can use the constructor to set DOMDocument properties.

$result = ArrayToXml::convert(
   $array, 
   $rootElement, 
   $replaceSpacesByUnderScoresInKeyNames, 
   $xmlEncoding, 
   $xmlVersion, 
   ['formatOutput' => true]
);

Alternatively you can use setDomProperties

$arrayToXml = new ArrayToXml($array);
$arrayToXml->setDomProperties(['formatOutput' => true]);
$result = $arrayToXml->toXml();

XML Prettification

Call $arrayToXml->prettify() method on ArrayToXml to set XML in pretty form.

Example:

$array = [
    'Good guy' => [
        'name' => 'Luke Skywalker',
        'weapon' => 'Lightsaber'
    ],
    'Bad guy' => [
        'name' => 'Sauron',
        'weapon' => 'Evil Eye'
    ]
];
$arrayToXml = new ArrayToXml($array);

With prettification:

$arrayToXml->prettify()->toXml();

will result in:

<?xml version="1.0"?>
<root>
    <Good_guy>
        <name>Luke Skywalker</name>
        <weapon>Lightsaber</weapon>
    </Good_guy>
    <Bad_guy>
        <name>Sauron</name>
        <weapon>Evil Eye</weapon>
    </Bad_guy>
</root>

Without prettification:

$arrayToXml->toXml();

will result in:

<?xml version="1.0"?>
<root><Good_guy><name>Luke Skywalker</name><weapon>Lightsaber</weapon></Good_guy><Bad_guy><name>Sauron</name><weapon>Evil Eye</weapon></Bad_guy></root>

Dropping XML declaration

Call $arrayToXml->dropXmlDeclaration() method on ArrayToXml object to omit default XML declaration on top of the generated XML.

Example:

$root = [
    'rootElementName' => 'soap:Envelope',
    '_attributes' => [
        'xmlns:soap' => 'http://www.w3.org/2003/05/soap-envelope/',
    ],
];
$array = [
    'soap:Header' => [],
    'soap:Body' => [
        'soap:key' => 'soap:value',
    ],
];
$arrayToXml = new ArrayToXml($array, $root);

$result = $arrayToXml->dropXmlDeclaration()->toXml();

This will result in:

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"><soap:Header/><soap:Body><soap:key>soap:value</soap:key></soap:Body></soap:Envelope>

Testing

vendor/bin/phpunit

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

License

The MIT License (MIT). Please see License File for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].