Posted By

Pjotor on 01/28/11


Tagged

mysql Converter json result


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

rmethod
summer_charlie
robertstefan
tux-world


mysql2json


 / Published in: PHP
 

URL: http://pjotor.com

Converts a MySQL result set to a JSON object, and ensures that the data is UTF-8 encoded. Usage: $conv = new mysql2json(); $JSONresult = $conv->getJSON($result);

Depends on an open link to the database.

  1. class mysql2json{
  2. function getJSON($result){
  3. $rows = array("data"=>array());
  4.  
  5. if(get_resource_type($result) != "mysql result")
  6. return json_encode($rows);
  7.  
  8. while($r = mysql_fetch_assoc($result))
  9. $rows['data'][] = $r;
  10.  
  11. for($i = 0, $size = sizeof($rows['data']); $i < $size; $i++)
  12. foreach($rows['data'][$i] as $key => $value)
  13. $rows['data'][$i][$key] = $this->noReturns(
  14. $this->decodeString( $value )
  15. )
  16. );
  17.  
  18. return json_encode($rows);
  19. }
  20.  
  21. function decodeString($s) {
  22. if( mb_detect_encoding($s,"UTF-8, ISO-8859-1, GBK")=="UTF-8" )
  23. $s = utf8_decode($s);
  24.  
  25. return $s;
  26. }
  27.  
  28. function noReturns($s) { return str_ireplace(array("\n","\r","\t"),"",$s); }
  29. }

Report this snippet  

You need to login to post a comment.