PHP arrays & recordsets to Javascript Objects (JSON)

Whilst writing the code for our MSG-Moodle integration, I needed to write a couple of helper functions to turn PHP arrays and ADOdb recordsets into JSON objects, and thought other might find them useful, so here they are:

This one takes an associative array of objects to turn into JSON object:

/**
* @param $objects object to turn into JSON
* @param $name overall name of the JSON object
* @param $callback name of the callback function
* @return string of the JSON object
*/
function phpToJSON($objects,$name,$callback=''){
$str = '';
if ($callback != ''){
$str .= $callback.'(';
}
if ($objects){
$str .= '{"'.$name.'":[';
$okeys = array_keys($objects);
for ($i=0; $i< sizeof($okeys); $i++){
$myobj = $objects[$okeys[$i]];
$attr = get_object_vars($myobj);
$str .= '{';
$keys = array_keys($attr);
for($j=0;$j< sizeof($keys); $j++){
$str .= '"'. $keys[$j] .'":"'. $attr[$keys[$j]] .'"';
if ($j != (sizeof($keys)-1)){
$str .= ',';
}
}
$str .= '}';
if ($i != (sizeof($objects)-1)){
$str .= ',';
}
}
$str .= ']}';
}
if ($callback != ''){
$str .= ');';
}
return $str;
}

and this one takes an ADOdb recordset and turns it into JSON object:

/**
* @param $objects object to turn into JSON
* @param $name overall name of the JSON object
* @param $callback name of the callback function
* @return string of the JSON object
*/
function phpRSToJSON($rs,$name,$callback=''){
$str = '';
if ($callback != ''){
$str .= $callback.'(';
}
if ($rs){

$str .= '{"'.$name.'":[';

$i=0;
while(!$rs->EOF) {
$i++;
$str .= '{';
$keys = array_keys($rs->fields);
for($j=0;$jfields[$keys[$j]] .'"';
if ($j != (sizeof($keys)-1)){
$str .= ',';
}
}
$str .= '}';
if ($i != $rs->RecordCount()){
$str .= ',';
}
$rs->MoveNext();
}

$str .= ']}';
}
if ($callback != ''){
$str .= ');';
}
return $str;
}

Hope you find these useful, and if you spot anything wrong (or that could be done better!) – please feel free to let me know 🙂

One Comment

  1. tony says:

    I have been using the ADODB variant and there appears to be bug here:

    if ($j != (sizeof($keys)-1)){
    $str .= ‘,’;
    }
    }
    $str .= ‘}’;
    if ($i != $rs->RecordCount()){
    $str .= ‘,’;

    Depending on the query, the JSON string usually has a trailing , (comma), which notoriously fails silently when using eval() or jquery library to render it.. because no error is generated by eval (javascript), its particulalry difficult to troubleshoot.

Leave a Reply