Categories
PHP

Array to XML in PHP

Do you need to convert an array to XML?

We do not have something to do it directly as we will do with json_encode. But with a small search you can find few solutions.

Have tried different ones, this one seems the one that works the best and quite elegant still.

/**
* Converts an array to XML
*
* @param array $array
* @param SimpleXMLElement $xml
* @param string $child_name
*
* @return SimpleXMLElement $xml
*/
public function arrayToXML($array, SimpleXMLElement $xml, $child_name)
{
    foreach ($array as $k => $v) {
        if(is_array($v)) {
            (is_int($k)) ? $this->arrayToXML($v, $xml->addChild($child_name), $v) : $this->arrayToXML($v, $xml->addChild(strtolower($k)), $child_name);
        } else {
            (is_int($k)) ? $xml->addChild($child_name, $v) : $xml->addChild(strtolower($k), $v);
        }
    }

    return $xml->asXML();
}
$this->arrayToXML($array, new SimpleXMLElement(''), 'child_name_to_replace_numeric_integers');

I got it from stackoverflow where you can check other solutions.