87
81

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでExcelで開いても文字化けしないCSVを出力する

Last updated at Posted at 2013-11-26

最後にUTF-8からSJISに変換します。


//$dataがCSVで出力するデータ(キーがa,b,c,dの連想配列を想定)
foreach ($data as $key => $value) {
        //CSVに書きだす内容をカンマ区切りにする
        $csv .=  $value['a'] . ',';
        $csv .=  $value['b'] . ',';
        $csv .=  $value['c'] . ',';
        $csv .=  $value['d'] . ',';
        $csv .=  "\n"; 
    }
 

    header("Content-Type: application/octet-stream");
    //$filenameにファイル名を指定
    header("Content-Disposition: attachment; filename=$filename");
    //Excelで開くようにSJISにする
    echo mb_convert_encoding($csv,"SJIS", "UTF-8");

上記コードだと、改行・カンマが含まれていると正しいCSVが作成できないとご指摘頂いたので、修正。

<?php

$data = array('hoge,fuga', "hoge\nfuga");
$csv = '';
$filename = 'test.csv';

foreach ($data as $key => $value) {
    //カンマ対応
    $value = str_replace(',', '","', $value);
    //改行対応
    $value = str_replace("\n", chr(10), $value);
    $csv .=  $value . ',';
    $csv .=  "\n"; 
}

    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=$filename");
    echo mb_convert_encoding($csv,"SJIS", "UTF-8");

こちらの方法でも可能とのことです!

$fp = fopen('php://output', 'w');
stream_filter_prepend($fp,'convert.iconv.utf-8/cp932');
fputcsv($fp,$header);
foreach($rows as $row){
    fputcsv($fp,$row);
}
87
81
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
87
81

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?