简体   繁体   English

Php 将数组导出到 Windows CMD 中的 CSV?

[英]Php Export Array to CSV in Windows CMD?

is there a way to export an array into csv file via running the php script in Window's command prompt (cmd)?有没有办法通过在 Window 的命令提示符 (cmd) 中运行 php 脚本将数组导出到 csv 文件中?

To run the php script in cmd I use: C:\php\php.exe -f "C:\filename.php"要在 cmd 中运行 php 脚本,我使用: C:\php\php.exe -f "C:\filename.php"

Thanks in advance.提前致谢。

Update: I have tried the following, which doesn't seem to work in a cmd setting.更新:我尝试了以下方法,这似乎不适用于 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);
}

I would use something like this:我会使用这样的东西:

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

That function would create the file if not exists with the content inside.如果文件不存在,则 function 将创建包含内容的文件。 You don't need to download it.你不需要下载它。 Enter the script.php directory and execute php script.php ;进入script.php目录,执行php script.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM