I use json_encode() a lot for AJAX calls. Teamed with jQuery’s $.getJSON(), it’s too convenient not to use. Unfortunately, json_encode() doesn’t come standard until PHP 5.2. To add insult to injury, many current *nix distros don’t include PHP 5.2 in their official repositories yet.
So, if you’re using PHP4 download JSON’s json_encode and json_decode for PHP4 (which automatically degrade for PHP5, thus not breaking your app during an upgrade) here:
http://mike.teczno.com/JSON/JSON.phps
json_encode() example 1
<?php
include("JSON.php");
$a = json_encode( array( 'a'=>1, '2'=>2, 'c'=>'I <3 JSON' ) );
echo $a;
// Outputs: {"a":1,"b":2,"c":"I <3 JSON"}
$b = json_decode( $a );
echo "$b->a, $b->b, $b->c";
// Outputs: 1, 2, I <3 JSON
json_encode() / json_decode() example 2
In Javascript, consuming input in JSON format is as easy as:
eval("var decoded_data = " + encoded_data);
With JSON-PHP, it can be almost as easy on the server-side, too:
// create a new instance of Services_JSON
require_once('JSON.php');
$json = new Services_JSON();
// convert a complex value to JSON notation
$value = array(1, 2, 'foo');
$output = $json->encode($value);
print($output);
// accept incoming POST data
$input = $GLOBALS['HTTP_RAW_POST_DATA'];
$value = $json->decode($input);
Using json_encode() and json_decode() in PHP4 with Arrays
You can use json_encode() with arrays or multi-dimensional arrays. When you are ready to output it as json, just call
echo json_encode($yourArray);
You can also use this method with jQuery’s $.ajax call, and specify the data type as JSON, although jQuery will automatically try and detect the data type, so that may not even be necessary.
source: mike.teczno
Pingback: how to use json_encode() on a php array, and also how to use jQuery.getJSON()?
Pingback: how to use json_encode() on a php array, and also how to use jQuery.getJSON()? | SeekPHP.com
Pingback: Tutorial menggunakan JqGird « rioruslan