remove old readme
[atutor.git] / mods / _standard / patcher / include / json.inc.php
1 <?php
2 /************************************************************************/
3 /* ATutor                                                               */
4 /************************************************************************/
5 /* Copyright (c) 2002-2010                                              */
6 /* Inclusive Design Institute                                           */
7 /* http://atutor.ca                                                     */
8 /*                                                                      */
9 /* This program is free software. You can redistribute it and/or        */
10 /* modify it under the terms of the GNU General Public License          */
11 /* as published by the Free Software Foundation.                        */
12 /************************************************************************/
13
14 // my simple JSON encode/decode function, similar to PHP5.2 
15 function json_encode_result($phpdata) {
16         if(gettype($phpdata) == "resource") 
17                 return php2js_sqlresult($phpdata);
18         else if(is_array($phpdata)) 
19                 return php2js_array($phpdata);
20         else
21                 return php2js_object($phpdata);
22 }
23
24
25 //function json_decode($jsonata) {
26 //      return $phpdata;
27 //}
28
29
30 // convert a PHP object to javascript object
31 function php2js_object($phpobj) {
32         $str = ""; 
33         
34         if (!is_array($phpobj)) return "[]";
35         
36         foreach($phpobj as $col => $val) {
37           if($str == "")
38             $str = $col .":'" . escapeString($val) . "'";
39           else
40             $str = $str . "," . $col .":'" . escapeString($val) . "'";
41         }
42         
43         return "{" . $str . "}";
44 }
45
46 // convert a PHP object to javascript object
47 function php2js_array($phparr) {
48         $str = "";
49
50   if (!is_array($phparr)) return "[]";
51
52         foreach ($phparr as $e) {
53           if($str == "") 
54                         $str = php2js_object($e) ;
55           else
56             $str = $str . "," . php2js_object($e);
57         }
58         
59         return "[" . $str . "]";
60 }
61
62 // convert a SQL result object to javascript object
63 function php2js_sqlresult($phpsql) {
64         // Printing results
65         $rows = array();
66         while ($line = mysql_fetch_assoc($phpsql)) {
67                 $rows[] = $line;
68         }
69         mysql_free_result($phpsql);
70         return php2js_array($rows);
71 }
72
73 function escapeString($string) {
74     $escape = array(
75     "\r\n" => '\n',
76     "\r"   => '\n',
77     "\n"   => '\n',
78     "/"    => '\/'
79     );
80
81     return str_replace(array_keys($escape), array_values($escape), addslashes($string));
82 }       
83
84 ?>