Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning JSON from a PHP Script

Tags:

json

php

header

I want to return JSON from a PHP script.

Do I just echo the result? Do I have to set the Content-Type header?

like image 636
Scott Nicol Avatar asked Oct 31 '10 18:10

Scott Nicol


People also ask

Can PHP return JSON?

You can simply use the json_encode() function to return JSON response from a PHP script. Also, if you're passing JSON data to a JavaScript program, make sure set the Content-Type header.

How can get curl output in JSON format in PHP?

To get JSON with Curl, you need to make an HTTP GET request and provide the Accept: application/json request header. The application/json request header is passed to the server with the curl -H command-line option and tells the server that the client is expecting JSON in response.

What is JSON response in PHP?

❮ Previous Next ❯ A common use of JSON is to read data from a web server, and display the data in a web page. This chapter will teach you how to exchange JSON data between the client and a PHP server.

What does json_decode return?

The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively. The NULL is returned if JSON can't be decoded or if the encoded data is deeper than the recursion limit.


2 Answers

While you're usually fine without it, you can and should set the Content-Type header:

<?php $data = /** whatever you're serializing **/; header('Content-Type: application/json; charset=utf-8'); echo json_encode($data); 

If I'm not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes print_r the data payload to eyeball it (though in most cases, it shouldn't be necessary).

like image 96
timdev Avatar answered Sep 20 '22 08:09

timdev


A complete piece of nice and clear PHP code returning JSON is:

$option = $_GET['option'];  if ( $option == 1 ) {     $data = [ 'a', 'b', 'c' ];     // will encode to JSON array: ["a","b","c"]     // accessed as example in JavaScript like: result[1] (returns "b") } else {     $data = [ 'name' => 'God', 'age' => -1 ];     // will encode to JSON object: {"name":"God","age":-1}       // accessed as example in JavaScript like: result.name or result['name'] (returns "God") }  header('Content-type: application/json'); echo json_encode( $data ); 
like image 41
aesede Avatar answered Sep 18 '22 08:09

aesede