Page 1 of 1

Returning JSON from a PHP Script

Posted: 24 Nov 2014, 13:25
by Marius
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?

Returning JSON from a PHP Script

Posted: 24 Nov 2014, 14:41
by MarPlo
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);