[英]Php Export Array to CSV in Windows CMD?
有沒有辦法通過在 Window 的命令提示符 (cmd) 中運行 php 腳本將數組導出到 csv 文件中?
要在 cmd 中運行 php 腳本,我使用: C:\php\php.exe -f "C:\filename.php"
提前致謝。
更新:我嘗試了以下方法,這似乎不適用於 cmd 設置。
function array_to_csv_download($OutputArray, $filename = "export.csv", $delimiter=";") {
$f = fopen('php://memory', 'w');
foreach ($OutputArray as $line) {
fputcsv($f, $line, $delimiter);
}
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'";');
fpassthru($f);
}
我會使用這樣的東西:
// file script.php
function array_to_csv_download($OutputArray, $filename = "export.csv", $delimiter=";") {
$lines= [];
foreach ($OutputArray as $row) {
$lines[]= implode($row, $delimiter);
}
$fileContent = implode($lines, "\n");
file_put_contents($filename, $fileContent);
}
$arrayToExport = [
["something", "to", "export"],
["something", "to", "export2"],
["something", "to", "export3"],
];
array_to_csv_download($arrayToExport);
如果文件不存在,則 function 將創建包含內容的文件。 你不需要下載它。 進入script.php目錄,執行php script.php
;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.