csv文件未在for循环中下载

时间:2017-06-29 12:12:51

标签: php fputcsv

比较两个多维数组并通过匹配值获得结果。如何为这些相应的值创建和下载csv文件。我已经尝试过以下代码

$mycsvfile_result = array();
foreach ($mycsvfile as $arr1)
{
   foreach ($mycsvfile_log as $arr2)
   {  
      if($arr2[2] == $arr1[0])
      {
         $mycsvfile_result[] = array($arr2[2], $arr2[7]);
      } 
   }                    
}

为fputcsv尝试了代码1

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="demo.csv"');
header('Pragma: no-cache');
header('Expires: 0');
    $fp = fopen('php://output', 'w');
      $data=$mycsvfile_result;
      foreach ( $data as $line ) 
      {
        fputcsv($fp, $line);
      }
    fclose($fp);
exit();

为fputcsv尝试了代码2

$csv = "col1,col2 \n";//Column headers
  foreach ($mycsvfile_result as $record)
  {
    $csv.= $record[0].','.$record[1]."\n"; //Append data to csv
  }
$csv_handler = fopen ('demo.csv','w');
fwrite ($csv_handler,$csv);
fclose ($csv_handler);
echo 'Data saved to demo.csv';

上面的代码1导致

id1,email1 id2,email2 id3,email3 

上面的代码2导致

col1,col2 id1,email1 id2,email2 id3,email3 Data saved to demo.csv

1 个答案:

答案 0 :(得分:0)

我在linux机器上工作,我忘了给文件夹权限上传csv文件。在给予文件夹权限后,它就像一个魅力:)