Returning JSON from a PHP Script

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts: 107

Returning JSON from a PHP Script

Hi
I have this array, and I want to return it as JSON from a PHP script.

Code: Select all

$ar = array(
  'k0'=> array('a', 'b', 'c'),
  'k1'=> array(1, 2, 3)
);
Do I just echo the result? Do I have to set header content-types?

MarPlo Posts: 186
Hi,
Use json_encode() to encode the data and set the content-type with header('Content-type: application/json');
Anyway, it works fine if you just "echo" the JSON string, without the header().

Code: Select all

$ar = array(
  'k0'=> array('a', 'b', 'c'),
  'k1'=> array(1, 2, 3)
);
header('Content-Type: application/json');    // Optional
echo json_encode($ar);