【问题标题】:Export csv file from array (php) with fputcsv in commando line, not browser使用命令行中的 fputcsv 从数组(php)导出 csv 文件,而不是浏览器
【发布时间】:2019-07-22 14:53:49
【问题描述】:

我编写了一个代码来将数组的数据导出到 csv 文件。但它只有在我在浏览器中打开脚本时才有效。我需要一个可以在命令行中运行的脚本,因为它是一个 cronjob。我只能显示脚本的最后一部分,其余的用于其他内容...

...... ......

$arrayCSV[]= array (
      "id" => $templateID,
      "state" => $templateState,
      "price" => $templatePrice,
      "exc_price" => $templateExc_price,
      "downloads" => $templateDownloads,
      "inserted_date" => $templateInsertedDate,
      "update_date" => $templateUpdateDate,
      "type" => $templateType,
      "author" => $templateAuthor,
      "live_preview_url" => $templateLivePreview,
      "screenshot_big" => $templateScreenshotBig,
      "screenshot_original" => $templateScreenshotOriginal,
      "screenshot_german" => $templateScreenshotGerman,
      "screenshot_responsive" => $templateScreenshotResponsive,
      "keywords" => $templateKeywords,
      "keywords_german" => $templateKeywordsGerman,
      "categories" => $templateCategories,
      "sources" => $templateSources,
      "features" => $templateFeatures,
      "template_name" => $templateName,
  );

};
$csvExportFile = 'gettemplates.csv';
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$csvExportFile");
$output = fopen("php://output", "w");
$header = array_keys($arrayCSV[0]);
fputcsv($output, $header);
foreach($arrayCSV as $row){
    fputcsv($output, $row);
}
fclose($output);

它在浏览器中工作,但我需要更改它,它只从它写入一个文件...

【问题讨论】:

  • 你需要输出到一个文件而不是输出到php://output,你不需要标题。
  • 是的,我想我明白了。但我是否需要将标题放在文件中,或者我只需要编写 $output = fopen($csvExportFile, "w");
  • 标题是对浏览器的说明:嘿浏览器,这是一个 CSV 文件。嘿浏览器,这是一个名为“gettemplates.csv”的附件。你不需要它们。只需:$output = fopen($csvExportFile, "w");(但请考虑保存文件的位置)。
  • 你是对的,我只改变了输出,它工作正常!感谢您的提示! $csvExportFile = 'gettemplates.csv'; $output = fopen($csvExportFile, "w"); $header = array_keys($arrayCSV[0]); fputcsv($output, $header); foreach($arrayCSV as $row){ fputcsv($output, $row); } fclose($output);

标签: php arrays csv fputcsv


【解决方案1】:

如果您需要csv文件中的header,只需将其添加到arrayCSV[],如下所示,然后写入您的csv文件:

$arrayCSV["header"] = "Content-type: text/csv";
$csvExportFile = 'gettemplates.csv';
$output = fopen($csvExportFile, "w");
foreach($arrayCSV as $row){
    fputcsv($output, $row);
}
fclose($output);

【讨论】:

    猜你喜欢
    • 2013-04-28
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多