CakePHP JSON渲染

时间:2014-08-05 07:36:22

标签: json cakephp

我不能为我的生活找出原因

$xml['interaction']['twitteraccount'] = 'hello';

使我的JSON输出呈现为HTML而不是JSON。我已经尝试了所有选项并且玩了一段时间。我当然错过了什么?只要我再次使用该行,它就会呈现为JSON!

public function lifestream()
{
    $this->RequestHandler->setContent('json', 'application/json' ); 

    $this->set('interactions', $this->Interaction->find('all'));

    $xmlArray = array();

    foreach($this->Interaction->find('all') as $interaction) {
        $sourceexploded = explode("/",$interaction['Interaction']['source']);

        if($sourceexploded[0] == "twitter") {
            $xml['interaction']['source'] = $sourceexploded[0];
            $xml['interaction']['twitteraccount'] = 'hello';
        } else {
            $xml['interaction']['source'] = $interaction['Interaction']['source'];
        }

        $xml['interaction']['timestamp'] = $interaction['Interaction']['timestamp'];
        $xml['interaction']['receivedfrom'] = $interaction['Interaction']['receivedfrom'];
        $xmlArray[] = $xml;
    }

    echo json_encode($xmlArray);

2 个答案:

答案 0 :(得分:3)

您必须使用JsonView。 在你的route.php中写道:Router::parseExtensions('json');

在您的控制器中,您必须设置RequestHandler组件。

class SomeNameController{

 public $components = array('RequestHandler');

 public function lifestream(){
   $this->RequestHandler->setContent('json', 'application/json' ); 
   $this->set('interactions', $this->Interaction->find('all'));
   $xmlArray = array();
   foreach($this->Interaction->find('all') as $interaction) {
    /* do stuff */
    $xmlArray[] = $xml;
   }
   $this->set('data', $xmlArray);
   $this->set('_serialize', array(
            'data', 
    ));
 }

}

尝试继续" samename / lifestream.json"现在或使用" Content-Type:application / json"。

发出HTTP请求

请注意:http://book.cakephp.org/2.0/en/views/json-and-xml-views.html

答案 1 :(得分:0)

添加以下两行代码:

$this->layout = 'ajax';
$this->autoRender = false;

第一行指示渲染使用名为ajax的空布局(您可以在Views / Layouts / ajax.ctp上找到它

第二个指示渲染器不查找视图模板(ctp文件)

然后,当您回显json_encode时,它将呈现为xml