Sunday, July 15, 2012

Save Your PHP in UTF-8 Format Without BOM

BOM or byte order mark is to indicate the byte order of your file. If your PHP file contains non-English characters, UTF-8 formatted PHP file will display as question mark(?) if the PHP script is run on Linux/Apache web service platform. However, no problem is found on Windows/IIS web servers. You can run the following PHP codes to check whether your PHP got BOM:


<?php

$handle = fopen('yourfilename.php','r');
$bom = fread($handle, 3);

if (empty($bom)) {
 echo("Error");
}
else if ($bom === chr(0xef).chr(0xbb).chr(0xbf)) {
 // UTF8 Byte Order Mark present
 echo("BOM");
}
else {
 echo("No BOM");
}

?>


If you see BOM in your UTF-8 PHP file, you'll need to convert to non-BOM format. You can easily fix it by editing using Notepad++. After opening your BOM PHP file, go to the "Encoding" menu and choose "Encode in UTF-8 without BOM". Then save the file.



Your PHP can now output non-English texts without any problem!

P.S.: (update on 18th of July 2012) You need to upload to the server as ASCII formatted file. I missed out this important info earlier. Sorry.

No comments:

Post a Comment