How to Ensure UTF8 Characters with fputcsv in PHP

Even when you config php.ini to output UTF8 characters for your PHP instance, you still need to ensure the fputcsv() function is outputting UTF8 characters

Rob Johnson

By Rob Johnson

Mon Nov 25 2019


I was working on a project where I transform data, create and load a CSV for another system to process. The issue was non-conforming characters were breaking the endpoint system. I ensured that my php.ini configuration had the UTF8 character set defined as default, however the output from fputcsv() was still outputting non-UTF8 characters.

I found the a Stack Overflow conversation and saw that the fix was to issue the following definitions in the fputcsv() function.

fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF));

The line fprintf($df, chr(0xEF).chr(0xBB).chr(0xBF)); writes file header for correct encoding.

Thanks goes to Hardy.

# commerce 14 # seo 5 # tools 6 # amazon 1 # sql 4 # shopify 9 # javascript 13 # projects 4 # css 2 # git 2 # php 3 # analytics 4 # api 6 # monitoring 2 # python 2 # aws 2