问题描述:

I would like my function to convert array of dimension N to xml, but it doesn't work.

Anyone can point me in the right direction?

function arrayToXml($array,$render = ""){

if(!is_array($array)){

return $array;

}

foreach ($array as $key => $value) {

if(is_array($value)){

$render .= '<' . $key . '>';

arrayToXml($value,$render);

}

else {

$render .= '<' . $key . '>';

$render .= $value;

$render .= '</' . $key . '>';

}

}

return $render;

}

Ok, I have found the solution:

function arrayToXml($array,$render = ""){

if(!is_array($array)){

return $array;

}

foreach ($array as $key => $value) {

if(is_array($value)){

$render .= '<' . $key . '>';

$render = arrayToXml($value,$render);

$render .= '</' . $key . '>';

}

else {

$render .= '<' . $key . '>';

$render .= $value;

$render .= '</' . $key . '>';

}

}

return $render;

}

网友答案:

You are not using the return value of arrayToXml($value,$render);, but you need to assign it to $render as well.

// …
if(is_array($value)){
    $render .= '<' . $key . '>';
    $render .= arrayToXml($value,$render);
}

Also note that tons of ready-to-use script can be found on the web to translate a PHP array into XML. For example http://snipplr.com/view/3491/.

相关阅读:
Top