MySQLi convert a result set to CSV or to JSON


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  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. }

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.