Normal Array to XML Format. Sometimes i ve the competetion in projects to parse to in differently formats i.e. API response formats (JSON,XML) and so on.
1.STEP
We
$data =
[
'status' => $exception->getStatus(),
'error' => $exception->getCode(),
'message' => $exception->getMessage(),
'errors' => $exception->getErrors()
];
2.STEP
Create SimpleXMLElement Object then pass addChild elements and then asXML does the rest.
$xmlobj = new SimpleXMLElement('<response/>');
Flip $data 😉 Keys and Values otherwise twisted
$toxml = array_flip($data);
array_walk_recursive($toxml, array ($xmlobj, 'addChild'));
echo $xmlobj->asXML();
Best Solution for Multidimensional Arrays
$xmlobj = new SimpleXMLElement('<response/>');
array2XML($obj, $data);
echo $xmlobj->asXML();
function array2XML($obj, $array)
{
foreach ($array as $key => $value)
{
if(is_numeric($key))
$key = 'item' . $key;
if (is_array($value))
{
$node = $obj->addChild($key);
$this->array2XML($node, $value);
}
else
{
$obj->addChild($key, htmlspecialchars($value));
}
}
}