bakedproject.com Blog Not just another WordPress weblog

29Oct/100

Baked json_encode… write your own for PHP 5.1.x

PHP's json_encode is a very handy function for encoding any associative array to JSON. This function comes bundled with PHP 5.2.x. I been working with a client who has PHP 5.1.6. I would install all the necessary tools, but client was not very willing to make changes and I been wanting to write my own JSON encoder for the longest time!

So here is my baked approach...

1
2
3
4
5
6
7
8
9
function my_json_encode($json_array) {
 $json = "[";
 for($i=0; $i1) $json .= ',';
   $json .= '"'.addslashes($key).'":"'.addslashes($row[$key]).'"';
  $i++;
 }
 $json .= "}";
 return $json;
}// end of my_json_encode

and the call

1
2
3
4
5
while($row = mysql_fetch_assoc($result)) {
 $json_row[] = $row;
} 
 
echo my_json_encode($json_row);

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.