无法将此php数组转换为xml

时间:2014-08-21 08:36:12

标签: php arrays xml cakephp cakephp-2.0

我正在使用cakephp v2.5。我想将数组转换为xml。数组看起来像这样;

$Items = array(
    (int) 0 => array(
        'Item' => array(
            'id' => '2'
        )
    ),
    (int) 1 => array(
        'Item' => array(
            'id' => '4'
        )
    )
)

要将此数组转换为xml,请运行以下php代码;

$xmlObject = Xml::fromArray(array('response' => $Items ));
echo $xmlObject->asXML();  

不幸的是,遇到以下错误;

Warning (2): SimpleXMLElement::__construct(): Entity: line 3: parser error : Extra content at the end of the document [CORE\Cake\Utility\Xml.php, line 221]

如何在php或cakephp(使用cake的内置函数)中将此数组转换为xml?

编辑:我发现了问题,但仍然没有解决方案。 array('response' => $Items)的输出会返回maximum depth reached条消息。有人可以提供建议吗?

2 个答案:

答案 0 :(得分:1)

尝试手动

//just initialize this array to a xml tags data.
//<id></id> so intialize it with id
// E.g. $tags_array = ('id');
$tags_array = $Row1[0]; //here $Row1[0] is my tags array.


foreach($tags_array as $tags)
{
    // Doing this thing because space xml tags will create a problem.
     $tags1     = str_replace(" ","_",$tags_array);
}

header('Content-type: text/xml');   
$output = "<?xml version=\"1.0\" ?>\n";
$output .= "<root>"; 

$total_tags=count($tags);

for($i=0; $i <= count($arr); $i++)
{   
  for($tag=0;$tag < $total_tags; $tag++)
   {
     $output .= '<'.$tags[$tag].'>';
     $output .= $arr[$i][$tag];
     $output .= '</'.$tags[$tag].'>';
   }
}
$output .= "</root>";

echo $output;

答案 1 :(得分:0)

$xmlObject = Xml::fromArray('response' => $Items );
 echo $xmlObject->asXML();  

这样做对我有用....试试我