Returning JSON response from Magento controller action

29 Ekim 2016 Cumartesi | | | Share on Google+
Here's quick example of how to return JSON response from Magento controller action. Assuming you have already created appropriate XML configuration and controller class/file, just add the following code to your action:
<?php

class ArchApps_JsonResponse_IndexController  
    extends Mage_Core_Controller_Front_Action
{
    /**
     * Example of single controller action returning JSON response
     */
    public function jsonAction()
    {
        // Data to be converted to JSON and returned as response
        $config = array('data' => array(1, 2, 3, 4, 5));

        // Make sure the content type for this response is JSON
        $this->getResponse()->clearHeaders()->setHeader(
            'Content-type',
            'application/json'
        );

        // Set the response body / contents to be the JSON data
        $this->getResponse()->setBody(
            Mage::helper('core')->jsonEncode($config)
        );
    }
}