function convertResult($rs, $type, $jsonmain="") { // receive a recordset and convert it to csv // or to json based on "type" parameter. $jsonArray = array(); $csvString = ""; $csvcolumns = ""; $count = 0; while($r = mysql_fetch_row($rs)) { for($k = 0; $k < count($r); $k++) { $jsonArray[$count][mysql_field_name($rs, $k)] = $r[$k]; $csvString.=","".$r[$k]."""; } if (!$csvcolumns) for($k = 0; $k < count($r); $k++) $csvcolumns.=($csvcolumns?",":"").mysql_field_name($rs, $k); $csvString.="n"; $count++; } $jsondata = "{"$jsonmain":".json_encode($jsonArray)."}"; $csvdata = str_replace("n,","n",$csvcolumns."n".$csvString); return ($type=="csv"?$csvdata:$jsondata); }
نحوه ی استفاده :
//... connect ... $sql = "select * from users limit 0,10"; $rs = mysql_query($sql); $jsonString = convertResult($rs,"json","users"); // json encoded string $csvString = convertResult($rs,"csv"); // scv output