jgreenawalt
jgreenawalt

Reputation: 253

Loading JSON with PHP

I've been using PHP for too long, but I'm new to JavaScript integration in some places.

I'm trying to find the fastest way to pass database information into a page where it can be modified and displayed dynamically in JavaScript.

Right now, I'm looking at loading a JSON with PHP echo statements because it's fast and effective, but I saw that I could use PHP's JSON library (PHP 5.2).

Has anybody tried the new JSON library, and is it better than my earlier method?

Upvotes: 7

Views: 2725

Answers (3)

Sean
Sean

Reputation: 7670

Library has worked great for me. FWIW I needed to do this on a project with earlier version of PHP lacking JSON support. Function below worked as a granted risky version of "json_encode" for arrays of strings.

function my_json_encode($row) {
    $json = "{";
        $keys = array_keys($row);
        $i=1;
        foreach ($keys as $key) {
            if ($i>1) $json .= ',';
            $json .= '"'.addslashes($key).'":"'.addslashes($row[$key]).'"';
            $i++;
        }
    $json .= "}";
    return $json;
}

Upvotes: 2

SchizoDuckie
SchizoDuckie

Reputation: 9401

the json_encode and json_decode methods work perfectly. Just pass them an object or an array that you want to encode and it recursively encodes them to JSON.

Make sure that you give it UTF-8 encoded data!

Upvotes: 4

John Millikin
John Millikin

Reputation: 200806

Use the library. If you try to generate it manually, I predict with 99% certainty that the resulting text will be invalid in some way. Especially with more esoteric features like Unicode strings or exponential notation.

Upvotes: 16

Related Questions