PHP printing JSON


I have very weird situation where JSON is not working only if generated and printed from PHP.
However, if I copy the result from the web browser and paste it on the bottom of the PHP file it works.

For instance,

<? print $json = "{\"sensor1\":\"1\",\"sensor2\":\"13\"}"; ?>

is not working. However, if I paste the result of above code from the web browser and paste it into following way works.

<? //print $json = "{\"sensor1\":\"1\",\"sensor2\":\"13\"}"; ?>

Anyone have any clue? Can anyone help me to resolve this strange issue?

ps. PHP header was sent as JSON. Also, there is no spaces in the json printed off the PHP.

You're best off using json_encode:

$data = array(
  "Sensor 1" => 48,
  "Sensor 2" => 209

print json_encode($data);

Thank you, Majenko. I will try again.


That works. Thanks a lot.