php字符串编码相互转换函数(GBK/UTF-8)

虽然说php自带了编码转换函数,但是在使用时会碰到字符丢失问题了,为了解决这个问题小编整理了两上将非GBK字符集的编码转为GBK与将非UTF-8字符集的编码转为UTF-8的函数,希望能帮助到各位.

例子代码如下:

  1. <?php
  2. /**
  3. * 将非GBK字符集的编码转为GBK
  4. *
  5. * @param mixed $mixed 源数据
  6. *
  7. * @return mixed GBK格式数据
  8. */
  9. function charsetToGBK($mixed)
  10. {
  11. if (is_array($mixed)) {
  12. foreach ($mixed as $k => $v) {
  13. if (is_array($v)) {
  14. $mixed[$k] = charsetToGBK($v);
  15. } else {
  16. $encode = mb_detect_encoding()($v, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
  17. if ($encode == 'UTF-8') {
  18. $mixed[$k] = iconv('UTF-8', 'GBK', $v);
  19. }
  20. }
  21. }
  22. } else {
  23. $encode = mb_detect_encoding($mixed, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
  24. //var_dump($encode);
  25. if ($encode == 'UTF-8') {
  26. $mixed = iconv('UTF-8', 'GBK', $mixed);
  27. }
  28. }
  29. return $mixed;
  30. }
  31. /**
  32. * 将非UTF-8字符集的编码转为UTF-8
  33. *
  34. * @param mixed $mixed 源数据
  35. *
  36. * @return mixed utf-8格式数据
  37. */
  38. function charsetToUTF8($mixed)
  39. {
  40. if (is_array($mixed)) {
  41. foreach ($mixed as $k => $v) {
  42. if (is_array($v)) {
  43. $mixed[$k] = charsetToUTF8($v);
  44. } else { //开源软件:phpfensi.com
  45. $encode = mb_detect_encoding($v, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
  46. if ($encode == 'EUC-CN') {
  47. $mixed[$k] = iconv('GBK', 'UTF-8', $v);
  48. }
  49. }
  50. }
  51. } else {
  52. $encode = mb_detect_encoding($mixed, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
  53. if ($encode == 'EUC-CN') {
  54. $mixed = iconv('GBK', 'UTF-8', $mixed);
  55. }
  56. }
  57. return $mixed;
  58. }
  59. ?>