php数组到csv不适用于下载文件

In a wordpress woocommerce installation I need to export some custom order fields to a csv file. Everything works fine, only I don't get the right content in the downloaded file.

Here is my code:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename="'.$filename.'"');
  $output = fopen( get_temp_dir() . $filename, 'w');
  foreach ($array as $line) { 
    fputcsv( $output, $line );
  }
  fclose($output);
}

The array is something like

$array = array(
  array('Head1', 'Head2', 'Head3', 'Head4'),
  array('Data1', 'Data2', 'Data3', 'Data4'),
  array('Data5', 'Data6', 'Data7', 'Data8')
);

The function is located on a custom admin page, and is triggered by a submit button.

When I press the button, a csv file is generated and written to the temp folder, named as $filename. That file works fine.

The file, which is downloaded automatically, forced by the second header entry in the function, is named correctly ($filename), but the content is the source code of that custom admin page.

I don't need that file to be stored in the temp folder, it's only for now until the automatic download works. I tried to put 'php://temp' or 'php://output' in the fopen function, but that didn't change the content of the download file.

What am I missing?

$data = array(
    array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25),
    array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18),
    array("firstname" => "James", "lastname" => "Brown", "age" => 31),
    array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7),
    array("firstname" => "Michael", "lastname" => "Davis", "age" => 43),
    array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24),
    array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27)
  );

  function cleanData(&$str)
  {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/?
/", "\
", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

  // file name for download
  $filename = "website_data_" . date('Ymd') . ".csv";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.csv");

  $flag = false;
  foreach($data as $row) {
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "
";
      $flag = true;
    }
    array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)) . "
";
  }

  exit;