文字コードを変えて一気に出力する方法(PHPのob_start)

ちょっと目に留まったので。
文字コードを変えて一気に出力する方法(PHPのob_start) | IDEA*IDEA


こんな感じでいいと思いました。

<?php
while(@ob_end_clean());
header('Content-Type: text/html; charset=Shift_JIS');
ob_start(create_function('&$buf', 'return mb_convert_encoding($buf, "SJIS", "UTF-8");'));
?>
<html>
<head></head>
<body>
ここにShift-JISで出力したい内容をUTF-8で記述。
</body>
</html>


それ以前に、ただのhtmlページならば、output_bufferingにmbのmb_output_handlerでいいと思うけど。


DoCoMoでCSSを効かせたい場合には、Content-Typeを application/xhtml+xmlで出す必要があるので、そういった場合には、使いどころがあると思います。
DoCoMoでCSSを効かせる方法 - maru.cc@はてな

<?php
// 以下の設定がされていることが前提
//output_handler	mb_output_handler
//mbstring.http_input	auto
//mbstring.http_output	SJIS
//mbstring.internal_encoding	UTF-8
//mbstring.language	Japanese
if (substr($_SERVER['HTTP_USER_AGENT'], 0, 11) == 'DoCoMo/2.0 ') {
  while(@ob_end_clean());
  header('Content-Type: application/xhtml+xml; charset=Shift_JIS');
  ob_start(create_function('&$buf', 'return mb_convert_encoding($buf, "SJIS", "UTF-8");'));
}
?>
<html>
<head></head>
<body>
ここにShift-JISで出力したい内容をUTF-8で記述。
</body>
</html>


もちろん、他のob_startでバッファリングしているフィルタがあるときには、ob_end_cleanのところとか注意が必要です。