82
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

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

最後に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);
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
82
Help us understand the problem. What are the problem?