douqiong8412 2012-01-22 01:40
浏览 111
已采纳

将二进制字符串写入文件

I m getting a request, when i use echo it prints it out on the shell and everything is awesome.

I want to write human readable string to file.

When i try to write these messages to file. i see binary string.

like this:

6^@8^@3^@7^@8^@1^@0^@,^@,^@1^@1^@b^@c^@d^@9^@0^@f^@-^@e^@3^@3^@a^@-^@4^@e^@0^@5^@-^@9^@e^@3^@d^@-^@5^@f^@a^@1^@8^@3^@4^@f^@d^@5^@e^@7^@,^@,^@:^@:^@1^@,^@M^@o^@z^@i^@l^@l^@a^@/^@5^@.^@0^@ ^@(^@W^@i^@n^@d^@o^@w^@s^@ ^@N^@T^@ ^@6^@.^@1^@;^@
 ^@W^@O^@W^@6^@4^@;^@ ^@r^@v^@:^@9^@.^@0^@.^@1^@)^@ ^@G^@e^@c^@k^@o^@/^@2^@0^@1^@0^@0^@1^@0^@1^@ ^@F^@i^@r^@e^@f^@o^@x^@/^@9^@.^@0^@.^@1^@,^@F^@i^@r^@e^@f^@o^@x^@,^@9^@.^@0^@,^@W^@i^@n^@d^@o^@w^@s^@,^@,^@0^@,^@0^@,^@0^@,^@0^@,^@0^@,^@,^@
 ^@:^@:^@1^@,^@ ^@1^@/^@2^@1^@/^@2^@0^@1^@2^@ ^@5^@:^@4^@5^@:^@5^@0^@ ^@P^@M^@

but i expect this:

6837817,,01497aed-181b-4054-b68f-3b41b4e707fc,,::1,Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1,Firefox,9.0,Windows,,0,0,0,0,0,, ::1, 1/21/2012 5:45:51 PM

ok i saw that there are methods like pack and unpack to get string from binary string but i failed.

<?php

$context = new ZMQContext();
$receiver = new ZMQSocket($context, ZMQ::SOCKET_PULL);
$receiver->bind("tcp://*:5557");

$fp = fopen('data.txt', 'w');

while(true){ 
$str = $receiver->recv();

echo $str."
";

file_put_contents('foo.txt', $str);

//fwrite($fp, $str."
");


}
fclose($fp);
?>

How can i get this done? I just wanted to write the string to file:(

Also, is this an expensive operation?

  • 写回答

2条回答 默认 最新

  • drwg89980 2012-01-22 03:20
    关注

    What you have there isn't binary data, but a different encoding for text. It's some form of UCS-2 I'd say. So you can "decode" it with:

     $string = iconv("UCS-2LE", "UTF-8", $string);
     file_put_contents(...);
    

    See iconv and UCS-2, BOM FF FE.

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

报告相同问题?

悬赏问题

  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?