Convert Recordset Untuk JSON Dan CSV

Fungsi ini mengubah rekord yang ditetapkan dan dikembalikan oleh fungsi mysql_query dalam bentuk string JSON atau ke string CSV.

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);
}

 

CONTOH:

//... 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

Leave a Reply

Your email address will not be published. Required fields are marked *


 

21