Returning JSON from a PHP Script

    |
  • Added:
  • |
  • In: Basic PHP

I want to return JSON from a PHP script.

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

This Question Has 11 Answeres | Orginal Question | Scott Nicol

As said above:

header('Content-Type: application/json'); 

will make the job. but keep in mind that :

  • Ajax will have no problem to read json even if this header is not used, except if your json contains some HTML tags. In this case you need to set the header as application/json.

  • Make sure your file is not encoded in UTF8-BOM. This format add a character in the top of the file, so your header() call will fail.

Try json_encode to encode the data and set the content-type with header('Content-type: application/json');.

Yeah, you'll need to use echo to display output. Mimetype: application/json

According to the manual on json_encode the method can return a non-string (false):

Returns a JSON encoded string on success or FALSE on failure.

When this happens echo json_encode($data) will output the empty string, which is invalid JSON.

json_encode will for instance fail (and return false) if its argument contains a non UTF-8 string.

This error condition should be captured in PHP, for example like this:

<?php header("Content-Type: application/json;charset=utf-8"); // Collect what you need in the $data variable. $json = json_encode($data); if ($json === false) { // Avoid echo of empty string (which is invalid JSON), and // JSONify the error message instead: $json = json_encode(array("jsonError", json_last_error_msg())); if ($json === false) { // This should not happen, but we go all the way now: $json = '{"jsonError": "unknown"}'; } // Set HTTP response status code to: 500 - Internal Server Error http_response_code(500); } echo $json; ?> 

Then the receiving end should of course be aware that the presence of the jsonError property indicates an error condition, which it should treat accordingly.

In production mode it might be better to send only a generic error status to the client and log the more specific error messages for later investigation.

Read more about dealing with JSON errors in Documentation

If you need to get json from php sending custom information you can add this header('Content-Type: application/json'); before to print any other thing, So then you can print you custome echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';

The answer to your question is here,

It says.

The MIME media type for JSON text is application/json.

so if you set the header to that type, and output your JSON string, it should work.

It is also good to set the access security - just replace * with the domain you want to be able to reach it.

<?php header('Access-Control-Allow-Origin: *'); header('Content-type: application/json'); $response = array(); $response[0] = array( 'id' => '1', 'value1'=> 'value1', 'value2'=> 'value2' ); } echo json_encode($response); ?> 

Here is more samples on that: how to bypass Access-Control-Allow-Origin?

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

You can use this little PHP library. It sends the headers and give you an object to use it easily.

It looks like :

<?php // Include the json class include('includes/json.php'); // Then create the PHP-Json Object to suits your needs // Set a variable ; var name = {} $Json = new json('var', 'name'); // Fire a callback ; callback({}); $Json = new json('callback', 'name'); // Just send a raw JSON ; {} $Json = new json(); // Build data $object = new stdClass(); $object->test = 'OK'; $arraytest = array('1','2','3'); $jsonOnly = '{"Hello" : "darling"}'; // Add some content $Json->add('width', '565px'); $Json->add('You are logged IN'); $Json->add('An_Object', $object); $Json->add("An_Array",$arraytest); $Json->add("A_Json",$jsonOnly); // Finally, send the JSON. $Json->send(); ?> 

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'); 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).

Document : Header json and the returned response

Set the content type with header('Content-type: application/json'); and then echo your data.


Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

NEED HOSTING?
Are you searching for Good Quality hosting?
You can Try It!
Connect Social With PHPAns
Top