Numeric Values in xml tag
I am trying to convert array to xml data in php. I am using xmlserializer pear package for this. My array is:
$arr=array(1000=>'name is john');
When I convert it to xml using this code:
options=array ('mode'=>'simplexml','addDecl'=>true,'indent'=>' ','rootName'=>'names');
$serializer = new XML_Serializer($options);
$result = $serializer->serialize($arr);
if($result == true)
$data=$serializer->getSerializedData();
echo $data;
I get following response:
<?xml version="1.0"?>
<names>name is john&l开发者_如何学Got;/names>
But I want this kind of response:
<?xml version="1.0"?>
<names>
<1000>name is john</1000>
</names>
can anyone tell where my mistake is?
I guess this is because numeric values are not allowed element names in XML. However, if you really want to have "xml-style" output like above (beside it is not real xml) you must bypass the library and code it by hand. I think this will do it for you:
public function xml_encode($array, $tag = "root"){
$result = '<'.$tag.'>';
foreach($array as $key => $value){
if(is_array($value)){
$result.=xml_encode($value, $key);
}else{
$result .= '<'.$key.'>'.$value.'</'.$key.'>';
}
}
$result .= '</'.$tag.'>';
return $result;
}
精彩评论