PHP Header json and the returned response


Example

By adding a header with content type as JSON:

<?php
 $result = array('menu1' => 'home', 'menu2' => 'code php', 'menu3' => 'about');

//return the json response :
header('Content-Type: application/json');  // <-- header declaration
echo json_encode($result, true);    // <--- encode
exit();

The header is there so your app can detect what data was returned and how it should handle it.
Note that : the content header is just information about type of returned data.

If you are using UTF-8, you can use :

header("Content-Type: application/json;charset=utf-8");

Example jQuery :

$.ajax({
        url:'url_your_page_php_that_return_json'        
    }).done(function(data){
        console.table('json ',data);
        console.log('Menu1 : ', data.menu1);
    });