Returning JSON from PHP to JavaScript?

AquinasTub picture AquinasTub · Mar 25, 2009 · Viewed 311k times · Source

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.

Answer

Kent Fredric picture Kent Fredric · Mar 25, 2009

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.