PHP UTF BOM 問題

VB.netからPHPを呼んで、そのレスポンスが
文字化けしていることがあった。
System.Text.Encoding.Unicode.GetBytes(str)
で確認すると、頭に「255」と「254」が付いていた。
PHPがUTF-8 BOM付 で保存されていたので、
BOM無 で保存し直すと解消した。
文字化けが発生した場合、関連するファイルがBOM付
でないか疑ってみると良いかも。

PHPで文字列をバイト変換は bin2hex
バイトから文字列は hex2bin(php5.4.0以上)

BOMの付いているファイルを探す

<?php

s('検索ディレクトリ/');


function s($target_dir) {
    chdir($target_dir);
    $files = glob('*');
    if (!is_array($files)||count($files)==0) return;
    foreach ($files as $file) {
        $path = $target_dir.$file;
        if (is_dir($path)) {
            s($path.'/');
        }else {
            $contents = file_get_contents($path);
            if (hasbom($contents)) {
                echo "<p>$path</p>";
            }
        }
    }
}

function hasbom($contents) {
    return preg_match("/^efbbbf/", bin2hex($contents[0] . $contents[1] . $contents[2])) === 1;
}