Returning JSON from PHP to JavaScript?

PhpJavascriptJson

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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:
    https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script/25062961#25062961
    This could be important to know in some cases as arrays and objects are not the same.

Solution 3 - Php

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}
?>

Solution 4 - Php

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.

Solution 5 - Php

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

Solution 6 - Php

$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). "}";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAquinasTubView Question on Stackoverflow
Solution 1 - PhpKent FredricView Answer on Stackoverflow
Solution 2 - PhpaesedeView Answer on Stackoverflow
Solution 3 - PhpÓlafur WaageView Answer on Stackoverflow
Solution 4 - PhpJukka DahlbomView Answer on Stackoverflow
Solution 5 - PhpAlexis PaquesView Answer on Stackoverflow
Solution 6 - PhpiamaspView Answer on Stackoverflow