Implementation details of PHP Chinese Character Transcoding

  • 2020-06-12 08:45:26
  • OfStack

As shown below:

<?php
function unicode_encode($str, $encoding='GBK', $prefix='&#', $postfix=';'){
 $str = iconv($encoding, 'UCS-2', $str);
 $arrstr = str_split($str, 2);
 $unistr = '';
 for($i=0, $len=count($arrstr); $i<$len; $i++)
 {
  $dec = hexdec(bin2hex($arrstr[$i]));
  $unistr .= $prefix.$dec.$postfix;
 }
 return $unistr;
}
$str = '<b> Ha ha </b>';
$unistr = unicode_encode($str);
echo $unistr.'<br />'; 
?>


Related articles: