Saturday, March 13, 2010

Converting CakePHP array to xml

Here is a small function to convert cakephp's array from find statements to xml.

function cakeArrayToXML($arr,$keyParent = "rows"){
$arrayRow = "<$keyParent>";
foreach($arr as $tkey => $trow){
$arrayRow .= $this->cakeArrayToXML($trow,"row");
$arrayRow .= $this->cakeArrayToXML($trow,$tkey);
$arrayRow .= "<$tkey><![CDATA[$trow]]></$tkey>";
$arrayRow .= "</$keyParent>";
return $arrayRow;

To use it you would do something like
header("Content-type: text/xml;charset:UTF-8");
echo '<?xml version="1.0" ?>';
echo $this->EcOutput->cakeArrayToXML($this->Lyric->find("all",array("limit"=>2)));

Output would be an xml with a parent node of rows and a node name of row on each row, i guess you just have to test it to understand what i mean, haha.
Hope it helps.