write into csv file in php

前端 未结 4 981
再見小時候
再見小時候 2021-01-06 17:43

I have to create and write into a csv file. Now I tried with the following code:

header(\'Content-type: application/octet-stream\');  
header(\'Content-dispo         


        
相关标签:
4条回答
  • 2021-01-06 18:11

    Try this:

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');
    
    $data = array (
        'aaa,bbb,ccc,ffffdd',
        '123,456,789',
        '"aaa","bbb"');
    
    
    $fp = fopen('php://output','w');
    foreach ($data as $line) {
        fputcsv($fp, array_map('utf8_decode',array_values($line)), ',', '"');
    }
    fclose($fp);
    
    0 讨论(0)
  • 2021-01-06 18:21

    Change the first header to header('Content-type: text/csv');

    0 讨论(0)
  • 2021-01-06 18:25

    header() needs to come after the array and fopen

    try this:

    $data = array (
        'aaa,bbb,ccc,ffffdd',
        '123,456,789',
        '"aaa","bbb"');
    $fp = fopen('php://output', 'w+'); 
    header('Content-type: application/octet-stream');  
    header('Content-disposition: attachment; filename="data.csv"'); 
    foreach($data as $line){
        $val = explode(",",$line);
        fputcsv($fp, $val);
    }
    fclose($fp);
    
    0 讨论(0)
  • 2021-01-06 18:26

    Wrap it in <?php and ?> tags.

    0 讨论(0)
提交回复
热议问题