Last Updated:

JSON in PHP

JSON is a simple format for serializing data into javascript, i.e. representing bonuses as a string. Similarly, in php, for example, there is a serialize() function, and in Java - RMI, in .NET - COM (if I am not mistaken), and in general form - XML.

Light weight

When php programmers did not yet know about the light weight of JSON, XML was used for the portability of the format. This is what FCKeditor does for example so far when retrieving the list in the resource manager. Another bad option is to transfer the finished HTML code immediately. But the size of the extra data in this case grows in a linear progression with the useful data/HTML tag coefficient.

Generation in PHP

On the backend in php 4, json is disabled by default, but you can try to enable it..

dl(json.so);

$strToSend=json_encode($objToEncode);

Another option is to use an object Services_JSON from bulky PEAR.

require_once('json.php');

$json = new Services_JSON();
$strToSend=$json->encode($objToEncode);

But as a rule, the first option does not work, and the second behaves strangely with utf8 encoding. So I had to slightly add a function to a variant that correctly encodes the new-line characters:

function array2json($arr) {
  $parts = array();
  $is_list = false;
  if (!is_array($arr)) return;
  if (count($arr)<1) return '{}';

  //Find out if the given array is a numerical array
  $keys = array_keys($arr);
  $max_length = count($arr)-1;
  //See if the first key is 0 and last key is length - 1
  if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {
    $is_list = true;
    for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position
      if($i != $keys[$i]) { //A key fails at position check.
        $is_list = false; //It is an associative array.
        break;
      }
    }
  }

  foreach($arr as $key=>$value) {
    if(is_array($value)) { //Custom handling for arrays
      if($is_list) $parts[] = array2json($value); /* :RECURSION: */
      else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
    } else {
      $str = '';
      if(!$is_list) $str = '"' . $key . '":';

      //Custom handling for multiple data types
      if(is_numeric($value)) $str .= $value; //Numbers
      elseif($value === false) $str .= 'false'; //The booleans
      elseif($value === true) $str .= 'true';
      else $str .= '"' . addslashes($value) . '"'; //All other things
      // :TODO: Is there any more datatype we should be in the lookout for? (Object?)

      $parts[] = $str;
    }
  }
  $json = implode(',',$parts);

  if($is_list) return '[' . $json . ']';//Return numerical JSON
  return '{' . $json . '}';//Return associative JSON
}

Prepare to take in the browser

In order for IE to understand the utf-8 encoding correctly, you need to specify the headers. Data can be transmitted both in plain text and headers (so that it would not be possible to directly see this from the browser)

header('Content-Type: application/json; charset=utf-8');
header('X-JSON: '.$myJsonData);

In Javascript, we get the text and decode it into data with the eval function. Also, do not forget to convert newline characters if they occur in the data. In many javascript libraries, functions for working with json, serialization of forms, etc. are already available.

//example for prototype.js
json = eval(t.getResponseHeader('X-JSON'));

//Example for jQuery
$.getJSON('/someJsonURL',function(json){
   json.descr=json.descr.replace(/\\n/g,"<br />");
   json.descr=json.descr.replace(/\\t/g,"\t");
}