【问题标题】:PHP Export to CSV from SQL ServerPHP 从 SQL Server 导出到 CSV
【发布时间】:2015-04-07 19:25:41
【问题描述】:

我需要一些帮助才能从 SQL Server 查询导出到 csv。

我有查询,但是当我获取结果时,我需要将它放在一个变量上并导出它。

这就是我所拥有的:

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

【问题讨论】:

  • 我不确定问题到底是什么。你可以说得更详细点吗?您在探索 csv 查询的哪一部分遇到问题?
  • 我需要将查询结果放入 $list 变量中,这就是我的问题所在,如何将其传递给 $list 变量。

标签: php sql-server csv odbc


【解决方案1】:

假设这是您的 sql,您可以执行以下操作以将数据从 mssql 导出到 .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;

【讨论】:

  • 谢谢您或您的回答。问候。
【解决方案2】:

你会想要这样的:

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

【讨论】:

  • 就是这样。非常感谢。
猜你喜欢
  • 2021-04-04
  • 2015-07-13
  • 1970-01-01
  • 2013-07-02
  • 1970-01-01
  • 2011-03-19
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
相关资源
最近更新 更多