Posted By

ginoplusio on 02/01/10


Tagged

mysql php csv json mysqli


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

liamchapman
ginoplusio


MySQLi convert a result set to CSV or to JSON


 / Published in: PHP
 

URL: http://www.barattalo.it/2010/01/29/10-php-usefull-functions-for-mysqli-improved-stuff/

  1. function convertResult($rs, $type, $jsonmain="") {
  2. // receive a recordset and convert it to csv
  3. // or to json based on "type" parameter.
  4. $jsonArray = array();
  5. $csvString = "";
  6. $csvcolumns = "";
  7. $count = 0;
  8. while($r = $rs->fetch_row()) {
  9. for($k = 0; $k < count($r); $k++) {
  10. $rs->field_seek($k);
  11. $finfo = $rs->fetch_field();
  12. $jsonArray[$count][$finfo->name] = $r[$k];
  13. $csvString.=",\"".$r[$k]."\"";
  14. if (!$count) $csvcolumns.=($csvcolumns?",":"").$finfo->name;
  15. }
  16. $csvString.="\n";
  17. $count++;
  18. }
  19. $jsondata = "{\"$jsonmain\":".json_encode($jsonArray)."}";
  20. $csvdata = str_replace("\n,","\n",$csvcolumns."\n".$csvString);
  21. return ($type=="csv"?$csvdata:$jsondata);
  22. }

Report this snippet  

You need to login to post a comment.