假設我已經將查詢存儲在名爲$ query的變量中。我想在結果頁面上創建一個名爲「以CSV格式導出」的小超鏈接。我該怎麼做呢?通過PHP將查詢結果導出爲CSV
7
A
回答
11
$query = "SELECT * FROM table_name";
$export = mysql_query ($query) or die ("Sql error : " . mysql_error());
$fields = mysql_num_fields ($export);
for ($i = 0; $i < $fields; $i++)
{
$header .= mysql_field_name($export , $i) . "\t";
}
while($row = mysql_fetch_row($export))
{
$line = '';
foreach($row as $value)
{
if ((!isset($value)) || ($value == ""))
{
$value = "\t";
}
else
{
$value = str_replace('"' , '""' , $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line) . "\n";
}
$data = str_replace("\r" , "" , $data);
if ($data == "")
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
5
ehm?
<a href="yourexport.php" title="export as csv">Export as CSV</a>
,如果你正在尋找腳本至極可以這樣做:
$myArray = array();
$fp = fopen('export.csv', 'w');
foreach ($myArray as $line) {
fputcsv($fp, split(',', $line));
}
fclose($fp);
3
CSV =逗號分隔值=用逗號
你有迴音/打印結果線分開你的價值觀按行分隔,用逗號(,)分隔。
我假設你的$查詢結果集查詢,這是一個關聯數組:
while($query = mysql_fetch_assoc($rs)) {
// loop till the end of records
echo $query["field1"] . "," . $query["field2"] . "," . $query["field3"] . "\r\n";
}
其中$ RS是資源句柄。
讓瀏覽器彈出一個下載框,你必須在文件的開頭設置頁眉(假設你的文件名是export.csv):
header("Expires: 0");
header("Cache-control: private");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=export.csv");
這就是它!
p.s.這種方法不會在服務器中留下物理文件。如果您打算在服務器中生成文件,請使用傳統的fopen和fwrite函數。
相關問題
- 1. 將MYSQL查詢結果導出到.csv
- 2. sqlyog導出查詢結果爲csv
- 3. 將PHP變量結果導出爲CSV
- 4. 將HiveQL查詢的結果導出爲CSV時出錯?
- 5. 通過Google BigQuery API將查詢結果導出爲JSON
- 6. 將查詢導出爲CSV
- 7. MULE ESB將查詢結果導出爲CSV
- 8. 使用pymssql將SQL Server查詢結果導出爲CSV
- 9. tsql:如何將查詢結果導出爲.csv?
- 10. 無法將查詢結果導出爲neo4j中的csv
- 11. SalesForce:將SOQL查詢結果導出爲CSV
- 12. 將多個查詢結果導出到一個CSV csv
- 13. MySQL將查詢輸出導出爲CSV
- 14. 將MYSQL結果導出爲CSV
- 15. 將Python結果導出爲CSV
- 16. 將Elasticsearch結果導出爲CSV文件
- 17. 通過PHP導出到CSV
- 18. 將查詢結果轉換爲CSV
- 19. 將php查詢結果導出爲ascii txt文件
- 20. pyodbc:查詢結果爲CSV?
- 21. 將sql查詢結果從畫面導出到csv
- 22. delphi csv將查詢結果導出到tedit或tmemo框
- 23. netezza nzsql將查詢結果導出到csv文件
- 24. 如何將查詢結果導出到csv文件?
- 25. 以編程方式將MS Access查詢結果導出到CSV
- 26. 避免將查詢結果導出到.csv文件中
- 27. 將sql查詢結果導出到csv或excel
- 28. 如何將格式爲CSV的查詢結果從標準輸出中導出?
- 29. Solr將查詢導出爲CSV文件
- 30. 無法寫入查詢結果導出爲CSV文件的ColdFusion
ArneRie和您的答案組合完美無缺 – Arc 2009-11-04 11:28:56