PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

[FIXED] How can I export .csv file using with Japanese character code in PHP?

 April 19, 2022     laravel, php     No comments   

Issue

I'm trying to create a csv file using laravel and php. The database used to create the csv contains Japanese characters which I want to appear exactly the same in the file.

Below is the code I've tried so far, but the japanese characters still appear as symbols.

$headers = array(
    "Content-Encoding" => "sjis-win",
    "Content-type" => "text/csv; charset=sjis-win",
    "Content-Disposition" => "attachment; filename=User-List.csv",
    "Pragma" => "no-cache",
    "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
    "Expires" => "0"
);


$users= $this->users->orderBy('created_at', 'desc')->get();
$columns = array('氏名', '氏名(ローマ字)');

$callback = function() use ($users, $columns)
{
    $file = fopen('php://output', 'w');
    fputcsv($file, $columns);

    foreach($users as $user) {
        fputcsv($file, array($user->name, $user->name_alphabet));
    }
    fclose($file);
};

What am I missing? What needs to be changed to make the characters appear as Japanese automatically in the csv.


Solution

As the data your retrieving from the database is encoded in UTF-8, you will need to re-encode that data to match the encoding of your CSV file (SJIS-win).

You can use php's mb_convert_encoding() function to achieve this.

mb_convert_encoding($dataVariable, "SJIS-win", "UTF-8");

In your case you would use it as follows:

foreach($users as $user) {
    fputcsv($file, array(
        mb_convert_encoding($user->name, "SJIS-win", "UTF-8"), 
        mb_convert_encoding($user->name_alphabet, "SJIS-win", "UTF-8")
    ));
}

You may also need to re-encode the strings in your $columns = array('氏名', '氏名(ローマ字)') array too.



Answered By - Jeemusu
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing