A useful class to generate valid XML from a PHP array.
Run the following command in your project to get the class:
composer require sausin/xml-construct
Usage is simple
$xmlGen = new XmlConstruct('ROOT')
$string = $xmlGen->fromArray($array)->getDocument();
where $array
is the PHP array from which you need the XML to be generated.
(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).
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!
Initial inputs to the class were taken from php user contributed notes