PHP 下載文字檔(UTF-8轉BIG5)出現亂碼"嚜燐"
發表於 : 2014-06-26 15:59:47
原因是在Window執行的PHP或include的檔案中有BOM
可以用下列程式檢查那些檔案有BOM
http://forums.sugarcrm.com/f3/utf-8-bom ... les-60080/
使用CodeLobster 選存檔的格式UTF_8即可,不要UTF_8 WITH BOM
可以用下列程式檢查那些檔案有BOM
http://forums.sugarcrm.com/f3/utf-8-bom ... les-60080/
代碼: 選擇全部
<?php
$bad_files = array();
$directory = "."; // Current directory
$fix_file = FALSE; // Change to TRUE, if you want to automatically fix files with BOM mark
$recursive_check = TRUE;
scanDirectory($directory, $bad_files);
if (count($bad_files) > 0)
{
echo "<br><br><br>Found the following files with a bad BOM:<br>";
printResults($bad_files);
}
else
echo "No Errors Found";
function scanDirectory($directory, &$bad_files)
{
global $recursive_check;
$skip_directories = array(".", "..", "cache");
if ($handle = opendir($directory))
{
echo "Checking Directory: $directory<br>";
while (false !== ($file = readdir($handle)))
{
$fullFile = $directory . DIRECTORY_SEPARATOR . $file;
// Recursive Call for sub-directories.
if (is_dir($fullFile) && $recursive_check)
{
if (in_array($file, $skip_directories))
Continue;
scanDirectory($fullFile, $bad_files);
}
if (checkFile($fullFile, $file))
$bad_files[] = $fullFile;
}
closedir($handle);
}
}
function checkFile($file, $fileOnly)
{
global $fix_file;
if (!is_file($file))
return;
if (substr($fileOnly, -4) == ".log")
return;
echo " $fileOnly";
$isBad = FALSE;
$file_contents = file_get_contents($file, "+r");
$hex = bin2hex($file_contents);
$first_token = substr($hex, 0, 6);
if ($first_token == 'efbbbf')
{
$isBad = TRUE;
echo " ...FOUND ERROR<br>";
if ($fix_file)
fixFile($hex,$file);
}
else
echo " ...OK<br>";
return $isBad;
}
function printResults($results)
{
foreach ($results as $fileName)
echo "$fileName<br>";
}
function fixFile($hex, $file)
{
$fp = fopen($file, 'w');
$good = substr($hex, 6);
$good_string = pack('H*', $good);
fwrite($fp, $good_string);
fclose($fp);
}
?>