文字コードについて執筆していきたいと思います。8月18日記事
目次
それぞれ文字には文字コードというものが割り当てられています。その文字コードは表になっており、様々な文字が表の中である番号で割り当てられています。
PHPで文字コードを変換する関数はmb_convert_encoding関数というものを利用します。使い方は
mb_convert_encoding($str,"変換後の文字コード","変換前の文字コード")
になります。データベースとPHPの文字コードが異なっていた場合によく使用します。
フォーム
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>文字コードテスト</title> </head> <body> <form action="confirm.php" method="post"> <p>タイトル</p> <input type="text" name="title" size="30"> <p>内容</p> <textarea name="contents" cols="20" rows="4"></textarea> <br> <input type="submit" name="submit" value="送信"> </form> </body> </html>
表示側
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>文字コードテスト結果</title> </head> <body> <?php $title = $_POST["title"]; $contents = $_POST["contents"]; echo "utf-8からutf-8へ<br>"; echo mb_convert_encoding($title,"utf-8","utf-8"); echo "<br>"; echo mb_convert_encoding($contents,"utf-8","utf-8"); echo "<br>"; echo "<br>"; echo "euc-jpからeuc-jpへ<br>"; echo mb_convert_encoding($title,"euc-jp","euc-jp"); echo "<br>"; echo mb_convert_encoding($contents,"euc-jp","euc-jp"); echo "<br>"; echo "<br>"; echo "sjisからsjisへ<br>"; echo mb_convert_encoding($title,"sjis","sjis"); echo "<br>"; echo mb_convert_encoding($contents,"sjis","sjis"); echo "<br>"; echo "<br>"; echo "utf-8からeuc-jpへ<br>"; echo mb_convert_encoding($title,"euc-jp","utf-8"); echo "<br>"; echo mb_convert_encoding($contents,"euc-jp","utf-8"); echo "<br>"; echo "<br>"; echo "euc-jpからutf-8へ<br>"; echo mb_convert_encoding($title,"utf-8","euc-jp"); echo "<br>"; echo mb_convert_encoding($contents,"utf-8","euc-jp"); echo "<br>"; echo "<br>"; echo "utf-8からsjisへ<br>"; echo mb_convert_encoding($title,"sjis","utf-8"); echo "<br>"; echo mb_convert_encoding($contents,"sjis","utf-8"); echo "<br>"; echo "<br>"; echo "sjisからutf-8へ<br>"; echo mb_convert_encoding($title,"utf-8","sjis"); echo "<br>"; echo mb_convert_encoding($contents,"utf-8","sjis"); echo "<br>"; echo "<br>"; echo "番外:euc-jpからsjisへ<br>"; echo mb_convert_encoding($title,"sjis","euc-jp"); echo "<br>"; echo mb_convert_encoding($contents,"sjis","euc-jp"); echo "<br>"; echo "<br>"; echo "番外:sjisからeuc-jpへ<br>"; echo mb_convert_encoding($title,"euc-jp","sjis"); echo "<br>"; echo mb_convert_encoding($contents,"euc-jp","sjis"); echo "<br>"; echo "<br>"; ?> </body> </html>
文字化けが起きた際の原因追究代わりに使ってみてください。
以上