-1

i have write a code to export Data of an array to a csv file. But it only works, when i open the script in browser. I need a script that i can run in commando line because a cronjob. I can only show the last part of the script, the rest is for other things...

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

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

it works in browser, but i need to change it, that it only writes a file from it...

Peter
  • 11
  • 5
  • Instead of outputting to [php://output](https://www.php.net/manual/en/wrappers.php.php) you need to output to a file, and you don't need headers. – KIKO Software Jul 22 '19 at 14:56
  • yes, i think i understand. but did i need to put the header someway in the file, or i only need to write $output = fopen($csvExportFile, "w"); – Peter Jul 22 '19 at 15:01
  • The headers are instructions to the browser: Hey browser, this is a CSV file. Hey browser, this is an attachement named "gettemplates.csv". You don't need them. Just do: `$output = fopen($csvExportFile, "w");` (but think about the location where the file will be saved). – KIKO Software Jul 22 '19 at 15:05
  • You were right, i have schanged only the output and it works fine! Thanks for your Tip! `$csvExportFile = 'gettemplates.csv'; $output = fopen($csvExportFile, "w"); $header = array_keys($arrayCSV[0]); fputcsv($output, $header); foreach($arrayCSV as $row){ fputcsv($output, $row); } fclose($output);` – Peter Jul 22 '19 at 15:05

1 Answers1

0

If you need the header in the csv file, just add it to the arrayCSV[], as follows, and write to your csv file:

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