152

I have a PHP script that's being called through jQuery AJAX. I want the PHP script to return the data in JSON format to the javascript. Here's the pseudo code in the PHP script:

$json = "{";
foreach($result as $addr)
{
    foreach($addr as $line)
    {
        $json .= $line . "\n";
    }
    $json .= "\n\n";
}
$json .= "}";

Basically, I need the results of the two for loops to be inserted in $json.

6 Answers 6

209

Php has an inbuilt JSON Serialising function.

json_encode

json_encode

Please use that if you can and don't suffer Not Invented Here syndrome.

4
  • 2
    Excellent, thank you. I had actually looked this up before posting on SO, but I didn't think it would be available on my hosting.
    – AquinasTub
    Commented Mar 25, 2009 at 16:14
  • This 'answer' is not complete and rather un-useful. See the answer from aesede for more complete information.
    – Funk Doc
    Commented May 30, 2019 at 16:22
  • @FunkDoc the OP in question was stringing together JSON by hand, under the assumption that was their only choice. Knowing it wasn't their only choice was a suitable solution. There is no obligation that the end result of that JSON will be emitted as HTTP response. The "add a header" information, while useful for one situation, is not going to help you if what you're doing with that JSON isn't simply "return it verbatim to the web page". The question didn't add clarification to the usecase. Commented Jun 13, 2019 at 10:04
  • ( Additionally, setting the header is not strictly necessary for AJAX. Apologies if I seem abrupt, but the shade given by the word "'answer'' in quotes really just wound me up, it was 10 years ago, let it die already. I've moved on from PHP so long ago that the language I moved to I'm now also moving away from. ) Commented Jun 13, 2019 at 10:13
173

Here are a couple of things missing in the previous answers:

  1. Set header in your PHP:

    header('Content-type: application/json');
    echo json_encode($array);
    
  2. json_encode() can return a JavaScript array instead of JavaScript object, see:
    Returning JSON from a PHP Script
    This could be important to know in some cases as arrays and objects are not the same.

3
  • 5
    It is important to note that the data is echoed instead of returned! That bit me for a good while when first learning the concept. Because in general programming, almost everything is usually returned not "printed". Commented Oct 7, 2015 at 21:42
  • Hey @Juha, keep in mind that json_encode() (like all functions) always returns something (including NULL); you can print the data, process it and then print it, assing it to a variable for later use, save it to a file, etc... You can read more about return in PHP: Returning values. Also you can (and should!) check for what each function you don't know returns, see our example json_encode() it states Returns a JSON encoded string on success or FALSE on failure.
    – aesede
    Commented Oct 8, 2015 at 13:53
  • 1
    Back then, I was wondering why return json_encode($jsonArray); didn't work (AngularJS http.get didn't get anything), until I later noticed it :) Commented Oct 9, 2015 at 5:20
91

There's a JSON section in the PHP's documentation. You'll need PHP 5.2.0 though.

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

If you don't, here's the PECL library you can install.

<?php
    $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

    echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>
0
13

Usually you would be interested in also having some structure to your data in the receiving end:

json_encode($result)

This will preserve the array keys as well.

Do remember that json_encode only works on utf8 -encoded data.

4

You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.

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();
?>
3
  • Warning: Simple JSON for PHP is GPLv2 licensed, so your own code must be open-source in order to use it. Commented Feb 14, 2018 at 19:14
  • 1
    Now MIT license :) Commented Apr 3, 2018 at 14:38
  • 1
    @JamieBirch In practice I think you're misunderstanding how GPL works. If you were talking about AGPL, then you'd be onto something. But vast screeds of the internet are built on GPL software and are under no obligation to opensource their code, because they're not giving users any executable under their control, only providing an interface to it. The only obligation they have is that anyone they give digital copies of the project to must also be given source. Commented Jun 13, 2019 at 10:17
1

$msg="You Enter Wrong Username OR Password"; $responso=json_encode($msg);

echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";

Not the answer you're looking for? Browse other questions tagged or ask your own question.