sausin / xml-construct

Generate valid XML using array inputs in PHP

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Xml generator

Latest Version on Packagist Build Status Quality Score Scrutinizer Coverage StyleCI Total Downloads License: MIT

A useful class to generate valid XML from a PHP array.

Installation

Run the following command in your project to get the class:

composer require sausin/xml-construct

Usage with normal arrays

Usage is simple

Verbose way:

$xmlGen = new XmlConstruct('ROOT')

$string = $xmlGen->fromArray($array)->getDocument();

where $array is the PHP array from which you need the XML to be generated.

Quick:

(new XmlConstruct('ROOT'))->fromArray($f)->getDocument();

returns the XML string.

In both the above examples, ROOT is the root of the XML (i.e. the first element).

Usage with arrays when attributes are needed in XML

If used like this:

$array = ['KEY|ATTR|VAL' => 'VALUE'];

return (new XmlConstruct('ROOT'))->fromArray($f)->getDocument();

It will result in the following XML

<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
  <KEY ATTR="VAL">VALUE</KEY>
<ROOT>

You can add as many attributes as you like and they will all be added to the element. Neat!

Credits

Initial inputs to the class were taken from php user contributed notes

About

Generate valid XML using array inputs in PHP

License:MIT License


Languages

Language:PHP 100.0%