Auf der Seite: http://www.bin-co.com/php/scripts/sql2json/ findet man ein kleines PHP Script was Datenbankabfragen in JSON Objekte umwandelt.

Das Orginal ist für MySQL  aber mit ein paar Anpassungen ist es ebenfalls für MSSQL verwendbar:

function sql2json($query) {
 $data_sql = mssql_query($query) or die("'';//" . mssql_error());// If an error has occurred,
 //    make the error a js comment so that a javascript error will NOT be invoked
 $json_str = ""; //Init the JSON string.
 
 if($total = mssql_num_rows($data_sql)) { //See if there is anything in the query
   $json_str .= "[\n";
 
   $row_count = 0;
   while($data = mssql_fetch_assoc($data_sql)) {
     if(count($data) > 1) $json_str .= "{\n";
 
     $count = 0;
     foreach($data as $key => $value) {
       //If it is an associative array we want it in the format of "key":"value"
       if(count($data) > 1) $json_str .= "\"$key\":\"$value\"";
       else $json_str .= "\"$value\"";
 
       //Make sure that the last item don't have a ',' (comma)
       $count++;
       if($count > count($data)) $json_str .= ",\n";
     }
     $row_count++;
     if(count($data) > 1) $json_str .= "}\n";
 
     //Make sure that the last item don't have a ',' (comma)
     if($row_count < $total) $json_str .= ",\n";
   }
 
   $json_str .= "]\n";
 }
 
 //Replace the '\n's - make it faster - but at the price of bad redability.
 $json_str = str_replace("\n","",$json_str); //Comment this out when you are debugging the script
 
 //Finally, output the data
 return $json_str;
}

In den meisten Fällen ist die MSSQL Datenbank nicht UTF-8 kodiert. Soll die Ausgabe entsprechend umkodiert werden, hilft ein folgender Befehl:

$string = iconv('cp1252','utf-8',$string);

Natürlich muss die Ausgabe ebenfalls in UTF-8 geschehen. Der HTTP-Header der den Content-Type und das Encoding angibt wird durch die PHP header-Funktion gesetzt:

header("Content-Type: text/html; charset=utf-8");

2 Kommentare zu „sql2json() – Konvertiert SQL in JSON Strings“

  1. Super! Und wo kommend ie Verbindungsinformationen für die DB hin? Also welche DB auf dem Server, User, Password.

  2. Einfach vorher eine Datenbankverbindung per mysql_connect [1] aufbauen. Wenn man mehrere Datenbankverbindungen hat, dann kann man das natürlich in mysql_query() als zweiten Parameter ergänzen.

Kommentarfunktion geschlossen.

Nach oben scrollen