Magento/PHP: Convert your XML Object to Array
While developing shipment tracking using SimpleXML in magento, I came accross the requirement where I have to get all the XML tags as keys and all the data inside XML tags as values in array. Means I wanted to convert XML to an Array where I can display all the information in some decorative format.
So here is how I converted XML to Array without any kind of hardcoding.
PHP class method to convert xml to array
public function convertXmlObjToArr($obj, &$arr){
$children = $obj->children();
$executed = false;
foreach ($children as $elementName => $node){
if($arr[$elementName]!=null){
if($arr[$elementName][0]!==null){
$i = count($arr[$elementName]);
$this->convertXmlObjToArr($node, $arr[$elementName][$i]);
}else{
$tmp = $arr[$elementName];
$arr[$elementName] = array();
$arr[$elementName][0] = $tmp;
$i = count($arr[$elementName]);
$this->convertXmlObjToArr($node, $arr[$elementName][$i]);
}
}else{
$arr[$elementName] = array();
$this->convertXmlObjToArr($node, $arr[$elementName]);
}
$executed = true;
}
if(!$executed&&$children->getName()==””){
$arr = (String)$obj;
}
return;
}
Hope this helps!
#convert xml to array #magento #simplexml #simplexml to array