duanliao2310 2014-12-10 02:47 采纳率: 100%
浏览 40
已采纳

PHP从不同的编码页面中打开Unicode编码文件

I have a text file stored in a server which is encoded in UTF-8 and im trying to load that file from a webpage in another server which is encoded in shift_JIS. I cant get it to work though. This is my original code:

function whatever() {
 $open_file = fopen("http://www.myass.com/whatever.txt", 'r');
 $whatevers = explode("*", fgets($open_file));
 $whatevers_num =count($whatevers)-2;
 $i=1;
 while($i <= $whatevers_num) {
   $details = explode("|", $whatevers[$i++]);
   echo <<<EOF
   $details[1] - $details[2] - $details[3]
EOF;
 }
  fclose($open_file);
}

I tried by doing this:

function whatever() {
 $open_file = fopen(mb_convert_encoding("http://www.myass.com/whatever.txt", "shift_jis"), 'r');
 $whatevers = explode("*", fgets($open_file));
 $whatevers_num =count($whatevers)-2;
 $i=1;
 while($i <= $whatevers_num) {
   $details = explode("|", $whatevers[$i++]);
   echo <<<EOF
   $details[1] - $details[2] - $details[3]
EOF;
 }
  fclose($open_file);
}

and even this:

function whatever() {
 $open_file = fopen("http://www.myass.com/whatever.txt", 'r');
 $whatevers = explode("*", fgets($open_file));
 $whatevers_num =count($whatevers)-2;
 $i=1;
 while($i <= $whatevers_num) {
   $details = explode("|", $whatevers[$i++]);
   echo <<<EOF
   $details[1] - $details[2] - $details[3]
EOF;
 }
  fclose($open_file);
}

ob_start();
whatever();
$get_whatever = ob_get_contents();
ob_end_clean();

$encode = mb_convert_encoding("$get_whatever", "shift_jis");

echo $encode;

but nothing worked, i get only garbled characters. What can i do?

Thank you.

  • 写回答

1条回答 默认 最新

  • dongmen5867 2014-12-10 04:04
    关注

    I would recommend loading the entire content of the file (using file_get_contents or CURL) into a string and converting it before doing any other type of processing. This ensures you have the full converted text at hand.

    $utf_string = file_get_contents('http://www.myass.com/whatever.txt');
    $sjis_string = mb_convert_encoding($utf_string, 'SJIS', 'UTF-8');
    echo($sjis_string);
    

    After this, you can start your explode and loop logic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图