PHP JSON Header json and the returned response

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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);
    });


Got any PHP Question?