PHP Export to CSV from SQL Server

﹥>﹥吖頭↗ 提交于 2019-12-20 06:03:19

问题


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:

$query = 'select * from sqlserver_table';
$result = odbc_exec($conMsSql,$query);

// this gives me the columns
while(odbc_fetch_row($result)){
        $field1 = odbc_result($result, 1);
        $field2 = odbc_result($result, 2);
        $field3 = odbc_result($result, 3);
        $field4 = odbc_result($result, 4);
        $field5 = odbc_result($result, 5);
        $field6 = odbc_result($result, 6);
        $field7 = odbc_result($result, 7);
    }


// this is to export
$file = fopen("export.csv","w");

foreach ($list as $line){   // how can I put the result in this variable ($list)?
    fputcsv($file,explode(',',$line));
}

fclose($file);

回答1:


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



回答2:


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($l AS $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;


来源:https://stackoverflow.com/questions/29499644/php-export-to-csv-from-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!