PHP - 导出CSV文件出错

时间:2017-07-27 08:47:57

标签: php

在PHP中导出CSV文件时,还会导出整页代码,之后只导出数据。

代码:

<?php

      header("Content-type: text/csv");
      header("Content-Disposition: attachment; filename=file.csv");
      header("Pragma: no-cache");
      header("Expires: 0");
      $data = array(
          array("data12", "data16", "data17"),
          array("data2", "data33", "data25"),
          array("data31", "data32", "data23")
      );   
      $file = fopen('php://output', 'w');                              
      fputcsv($file, array('Description', 'Click', 'CTR'));      

?>

enter image description here

1 个答案:

答案 0 :(得分:1)

您应该为csv文件准备数据(不要发送数组)。 另外我不知道csv文件中你想要的结果是什么。

试试这个

$data = array(
      array("data12", "data16", "data17"),
      array("data2", "data33", "data25"),
      array("data31", "data32", "data23")
    );
    $csvData = "Your header\n";
    foreach ($data as $row) {
      foreach($row as $dot) {
        $csvData .= $dot.';';
      }
    }
    $csvData = utf8_decode($csvData);
    header('Content-Type: application/csv; charset=UTF-8');
    header('Content-Disposition: attachement; filename="myfile.csv"');
    echo $csvData;
    exit();