Returning JSON from PHP to JavaScript?


Question

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.

1
128
3/25/2009 4:00:47 PM

Accepted Answer

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.

189
3/25/2009 4:02:53 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon