PHP - fwrite with UTF-8 encoding


Use fwrite() function to write an UTF-8 file:
An easy way to create a UTF-8 file in PHP, that can be useful in many cases for example if you want to translate data from a sql query to a CSV os TXT file and need the UTF-8 format .




//Add header with the UTF-8 Charset -- Agrega el encabezado indicando el juego de caracteres UTF-8 
header("Content-Type:text/html; charset=utf-8");

//Creates new file in write and save binary mode 
$file = fopen($fileName, 'wb');
 
//Add BOM to utf-8 -- Agrega formato BOM (Byte Order Mark)  
fwrite($file, pack("CCC",0xef,0xbb,0xbf));

//Add content to file 
fwrite($file, utf8_encode('abcdefgthijkÑñáéí');

//Close file -- Cierra el archivo
fclose($file);


Previous
Next Post »