145

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.

AquinasTub
  • 7,345
  • 6
  • 20
  • 14

6 Answers6

203

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.

Kent Fredric
  • 54,014
  • 14
  • 101
  • 148
  • 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 Mar 25 '09 at 16:14
  • This 'answer' is not complete and rather un-useful. See the answer from aesede for more complete information. – Funk Doc May 30 '19 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. – Kent Fredric Jun 13 '19 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. ) – Kent Fredric Jun 13 '19 at 10:13
156

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.

Community
  • 1
  • 1
aesede
  • 5,006
  • 2
  • 32
  • 32
  • 3
    It is important to note that the data is **echo**ed instead of **return**ed! That bit me for a good while when first learning the concept. Because in general programming, almost everything is usually returned not "printed". – Juha Untinen Oct 07 '15 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](http://php.net/manual/en/functions.returning-values.php). Also you can (and should!) check for what each function you don't know returns, see our example [json_encode()](http://php.net/manual/en/function.json-encode.php) it states _Returns a JSON encoded string on success or FALSE on failure._ – aesede Oct 08 '15 at 13:53
  • 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 :) – Juha Untinen Oct 09 '15 at 05:20
86

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}
?>
Ólafur Waage
  • 64,767
  • 17
  • 135
  • 193
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.

Jukka Dahlbom
  • 1,712
  • 2
  • 16
  • 23
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();
?>
Alexis Paques
  • 1,496
  • 12
  • 25
  • Warning: Simple JSON for PHP is GPLv2 licensed, so your own code must be open-source in order to use it. – Jamie Birch Feb 14 '18 at 19:14
  • 1
    Now MIT license :) – Alexis Paques Apr 03 '18 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. – Kent Fredric Jun 13 '19 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). "}";
iamasp
  • 47
  • 5