Skip to content Skip to sidebar Skip to footer

Php Export To Csv From Sql Server

I need some help to export from a SQL Server query to csv. I have the query but when I'm fetching the result I need to put it on an variable and export it. This is what I have: $q

Solution 1:

lets say this was your sql, you'd do the following to export data from mssql to .csv.

$sql = "SELECT * FROM target_database_table_name";

$results = mssql_query($sql, $db);
//Generate CSV file - Set as MSSQL_ASSOC as you don't need the numeric values.while ($l = mssql_fetch_array($results, MSSQL_ASSOC)) {
    foreach($lAS$key => $value){
        //If the character " exists, then escape it, otherwise the csv file will be invalid.$pos = strpos($value, '"');
        if ($pos !== false) {
            $value = str_replace('"', '\"', $value);
        }
        $out .= '"'.$value.'",';
    }
    $out .= "\n";
}
mssql_free_result($results);
mssql_close($db);
// Output to browser with the CSV mime type
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=table_dump.csv");
echo$out;

Solution 2:

You'd want something like this:

$csvName = "export.csv"$sqlQuery = 'select * from sqlserver_table';
$sqlRresult = odbc_exec($conMsSql, $sql);

$fp = fopen(csvName , 'w');

while ($export = odbc_fetch_array($sqlRresult)) {
    if (!isset($headings))
    {
        $headings = array_keys($export);
        fputcsv($fp, $headings, ',', '"');
    }
    fputcsv($fp, $export, ',', '"');
}
fclose($fp);

Post a Comment for "Php Export To Csv From Sql Server"