【问题标题】:PHP write binary responsePHP写二进制响应
【发布时间】:2012-06-16 20:14:54
【问题描述】:

在 php 中有没有办法将二进制数据写入响应流,
类似于 (c# asp)

System.IO.BinaryWriter Binary = new System.IO.BinaryWriter(Response.OutputStream);
Binary.Write((System.Int32)1);//01000000
Binary.Write((System.Int32)1020);//FC030000
Binary.Close();



然后我希望能够在 c# 应用程序中读取响应,例如

System.Net.HttpWebRequest Request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("URI");
System.IO.BinaryReader Binary = new System.IO.BinaryReader(Request.GetResponse().GetResponseStream());
System.Int32 i = Binary.ReadInt32();//1
i = Binary.ReadInt32();//1020
Binary.Close();

【问题讨论】:

    标签: php binary response


    【解决方案1】:

    在 PHP 中,字符串和字节数组是一回事。使用pack 创建一个字节数组(字符串),然后您可以编写它。一旦我意识到这一点,生活就会变得更轻松。

    $my_byte_array = pack("LL", 0x01000000, 0xFC030000);
    $fp = fopen("somefile.txt", "w");
    fwrite($fp, $my_byte_array);
    
    // or just echo to stdout
    echo $my_byte_array;
    

    【讨论】:

    • +1 表示对我有帮助的答案。我在下面添加对我有用的东西作为另一个答案。
    • 我更喜欢使用print() 而不是echo,因为它更像一个函数。不过,从技术上讲,两者都不是真正的功能。文档将它们称为“语言结构”。如果您需要文件描述符进行输出,在技术上也可以使用fopen("php://output")。详情请见php.net/manual/en/wrappers.php.php
    【解决方案2】:

    通常,我使用chr()

    echo chr(255); // Returns one byte, value 0xFF
    

    http://php.net/manual/en/function.chr.php

    【讨论】:

      【解决方案3】:

      这与我发布到 this, similar, question 的答案相同。

      假设数组$binary 是一个先前构造的数组字节(在我的例子中就像单色位图像素),您希望以这个确切的顺序写入磁盘,下面的代码在运行 ubuntu 服务器 10.04 的 AMD 1055t 上为我工作LTS。

      我遍历了我在网上可以找到的所有类型的答案,检查了输出(我使用了 shed 或 vi, like in this answer)来确认结果。

      <?php
      $fp = fopen($base.".bin", "w");
      $binout=Array();
      for($idx=0; $idx < $stop; $idx=$idx+2 ){
          if( array_key_exists($idx,$binary) )
              fwrite($fp,pack( "n", $binary[$idx]<<8 | $binary[$idx+1]));
          else {
              echo "index $idx not found in array \$binary[], wtf?\n";
          }
      }
      fclose($fp);
      echo "Filename $base.bin had ".filesize($base.".bin")." bytes written\n";
      ?>
      

      【讨论】:

        【解决方案4】:

        您可能需要pack 函数——它可以让您对值的结构也有相当程度的控制,即一次 16 位或 32 位,小端与大端,等等

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-12-11
          • 2020-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-31
          • 2020-04-21
          相关资源
          最近更新 更多