153

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

211

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
This 'answer' is not complete and rather un-useful. See the answer from aesede for more complete information.
@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.
( 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. )
179

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 Comments

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".
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.
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 :)
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}
?>

Comments

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.

Comments

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 Comments

Warning: Simple JSON for PHP is GPLv2 licensed, so your own code must be open-source in order to use it.
Now MIT license :)
@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.
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). "}";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.