php array數組產生csv檔案

來源:互聯網
上載者:User

 代碼如下 複製代碼

<?php
$data = array(
        array( 'row_1_col_1', 'row_1_col_2', 'row_1_col_3' ),
        array( 'row_2_col_1', 'row_2_col_2', 'row_2_col_3' ),
        array( 'row_3_col_1', 'row_3_col_2', 'row_3_col_3' ),
    );
$filename = "example";
 
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename={$filename}.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
 
outputCSV($data);
 
function outputCSV($data) {
        $outputBuffer = fopen("php://output", 'w');
        foreach($data as $val) {
        foreach ($val as $key => $val2) {
         $val[$key] = iconv('utf-8', 'gbk', $val2);// CSV的Excel支援GBK編碼,一定要轉換,否則亂碼
         }
            fputcsv($outputBuffer, $val);
        }
        fclose($outputBuffer);
    }
 
?>

例2

看一個讀取csv檔案的執行個體

讀取cvs,使用fgetcsv()檔案指標中讀入一行並解析 CSV 欄位

 比如說我要讀取如下csv檔案

 代碼如下 複製代碼

<?php
/** by www.111cn.net */
$row = 1;
$handle = fopen("file.csv","r");
//fgetcsv() 解析讀入的行並找出 CSV格式的欄位然後返回一個包含這些欄位的數組。
while ($data = fgetcsv($handle, 1000, ",")) {
    $num = count($data);
    echo "<p> $num fields in line $row: <br>n";
    $row++;
    for ($c=0; $c < $num; $c++) {
  //注意中文亂碼問題
  $data[$c]=iconv("gbk", "utf-8//IGNORE",$data[$c]); 
        echo $data[$c] . "<br>n";
    }
}
fclose($handle);
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.