在CakePHP中格式化我的XML输出

时间:2013-01-23 23:32:34

标签: xml cakephp

我的players表包含三个field idfirst_namelast_namePlayersController方法index显示表格中的每个玩家:

public function index() {
        $output = $this->Player->find('all');
        $this->set(array(
            'output' => $output,
            '_serialize' => array('output')
        ));
        $this->render('generic_response');
    }

,generic_response是一个XML视图,如下所示:

<?php
$xml = Xml::fromArray(array('response' => $output));
echo $xml->asXML();

生成的XML是:

<response>
  <output>
     <Player>
       <id>2</id>
       <first_name>Ciro</first_name>
       <second_name>Spee</second_name>
     </Player>
   </output>
   <output>
     <Player>
       <id>3</id>
       <first_name>Ugo</first_name>
       <second_name>Ridi</second_name>
     </Player>
   </output>
</response>

但我想要像:

<response>
  <players>
     <Player>
       <id>2</id>
       <first_name>Ciro</first_name>
       <second_name>Spee</second_name>
     </Player>
     <Player>
       <id>3</id>
       <first_name>Ugo</first_name>
       <second_name>Ridi</second_name>
     </Player>
   </players>
</response>

我该怎么做?

1 个答案:

答案 0 :(得分:2)

旧代码:

$output = $this->Player->find('all');
$this->set(array(
    'output' => $output,
    '_serialize' => array('output')
));

新代码:

$output = array(
    'Player' => Hash::combine(
        $this->Player->find('all'),
        '{n}.Player.id',
        '{n}.Player'
    )
);

$this->set(array(
    'players' => $output,
    '_serialize' => array('players')
));