Return json formatted entries and include a header for Access-Control-Allow-Origin Hi Not sure on the best way to do this. I have some javascript that requires a json formatted file to populate a calendar. I can do this in php by adding the following to the file that is being requested:

header('Access-Control-Allow-Origin: *');
    $array = array(
    array('date' =&gt; "27/9/2015", 'title' =&gt; 'BBC Event', 'link' =&gt; 'http://www.bbc.co.uk')
    );
echo json_encode($array);


I need to be able to do the same with craft. I have tried just formatting the entries in twig which returns the json as it should be but because the header is missing the javascript call does not run it. I have also created a small plugin to pull out all the entries which may be a better option. I just need to know how to return those entries in json to a template as per the above php would create with a header included.

Any help much appreciated.

Cheers
You can set the header in Twig with the {% header %} function. Like this:

{% header "Content-Type: application/json; charset=utf-8" %}
{% header "Access-Control-Allow-Origin: *" %}


As to generating the actual json, my favourite is using the prune plugin and do it like this:

{% set myEntries = craft.entries.section('mySection').find() %}

{
    {%- spaceless -%}
    "myEntries": {{ myEntries | prune(['onefield', 'anotherfield']) | json_encode() | raw }},
    {%- endspaceless -%}
}


You could also just loop over all the entries and create the json yourself, but I always get into all sorts of issues with encoding when doing that.

If you're going to do a lot of json requests, you could also look into the Element API plugin from Pixel &amp; Tonic. You'd probably have to set the headers on the webserver level (.htaccess or nginx.conf) though.