Skip to content

Instantly share code, notes, and snippets.

@darkogoles1
Last active August 23, 2017 19:07
Show Gist options
  • Select an option

  • Save darkogoles1/d27fea626659d7d50b547162ef359506 to your computer and use it in GitHub Desktop.

Select an option

Save darkogoles1/d27fea626659d7d50b547162ef359506 to your computer and use it in GitHub Desktop.
PHP / Magento Convert array to XML
<?php
class Helper_Xml
{
protected function _arrayToXmlRecursive($arrData, $addCdata = false, $parentKey = '', &$isNumericCallback = false)
{
$xml = '';
$xmlModel = new Varien_Simplexml_Element('<node></node>');
foreach ($arrData as $fieldName => $fieldValue) {
$isNumericChildArr = false;
if (!empty($parentKey) AND is_numeric($fieldName)) {
$fieldName = $parentKey;
}
if (is_array($fieldValue)) {
$isNumericChildArr = !$this->_isAssoc($fieldValue);
$fieldValue = $this->_arrayToXmlRecursive($fieldValue, $addCdata, $fieldName);
}
if ($addCdata === true) {
$fieldValue = "<![CDATA[$fieldValue]]>";
}
if ($isNumericChildArr) {
$xml .= "$fieldValue";
} else {
$xml .= "<$fieldName>$fieldValue</$fieldName>";
}
}
return $xml;
}
protected function _isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
public function toXml($arrData, $rootName = 'item', $addOpenTag = false, $addCdata = true)
{
$xml = '';
if ($addOpenTag) {
$xml .= '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
}
if (!empty($rootName)) {
$xml .= '<' . $rootName . '>';
}
$xml .= $this->_arrayToXmlRecursive($arrData, $rootName, $addOpenTag, $addCdata);
if (!empty($rootName)) {
$xml .= '</' . $rootName . '>';
}
return $xml;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment