duandou1903 2013-10-30 12:18
浏览 214
已采纳

php utf-8不起作用

I'm trying, put in header("Content-Type: text/html; charset=utf-8"); but not work

<?PHP
  header("Content-Type: text/html; charset=utf-8");
  function randStr($rts=20){ 
  $act_chars = "ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ"; 
  $act_val = ""; 
  for($act=0; $act <$rts ; $act++) 
  { 
     mt_srand((double)microtime()*1000000); 
     $act_val .= $act_chars[mt_rand(0,strlen($act_chars)-1)]; 
  } 

  return $act_val; 
  } 
  $dene = randStr(16);
  print "$dene";
  ?>

output

K��A�CÞZU����EJ
  • 写回答

3条回答 默认 最新

  • dongruan6001 2013-10-30 12:27
    关注

    There are several mistakes. Don't use [] or strlen() on a multibyte string. Use mb_substr() and mb_strlen().

    Also set the internal encoding of the multibyte extension to UTF-8:

    mb_internal_encoding("UTF-8");
    

    You could also set the encoding on a per-function basis. See the specific function signatures for further details.

    Here is an improved version of your code:

    header('Content-Type: text/html; charset=utf-8');
    mb_internal_encoding("UTF-8");
    
    function randStr($rts = 20) { 
      $act_chars = 'ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ';
      $act_val = '';
      $act_chars_last = mb_strlen($act_chars);
    
      for($act = 0; $act < $rts; $act++) { 
        $act_val .= mb_substr($act_chars, mt_rand(0, $act_chars_last), 1);
      } 
    
      return $act_val; 
    } 
    $dene = randStr(16);
    print $dene;
    

    • Replaced double quotes by single quotes (saves a tiny amount of time)

    • Removed mt_srand() calls because they are automatically done as of PHP 4.2.0 (thanks to feeela for mentioning that in a comment)

    • Saved the string length - 1 in a variable, so PHP doesn't need to recomputed it in every loop step.

    If you want more insights on that topic, checkout the link from deceze in the answer below: What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!