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

Nov 25, 2019

#php

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.