将PHP字符串转换为二进制格式,并在连接到服务器时重新转换它们

I'm looking to code a php script that would connect to a server using binary protocol, send queries and receive data from it. I wondered how I can implement this in php? So far I have:

<?php
$fp = fsockopen("111.111.10.10", "2222", $errno, $errstr, 10);
if (!$fp) {
    echo "$errstr ($errno)<br />
";
} else {
    fwrite($fp, "You message");
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

When I speak of binary, I don't mean the underlying of computer language, I mean that the specific string that is sent to the server should be converted in "0101001", since that is the way server reads and converts info. I need a way to convert php strings to this format and reconvert them back.

I will explain if you don't fully understand the question.

use pack and unpack to convert to/from binary

They already are in a binary representation. Transmitting them to the server via fwrite should be enough.

The other end of the socket will receive the binary string and process it as is.

To create a binary string from a string, you need a few steps. First change all charactors to numeric ord() and then convert the number to decimal decbin. I also used str_pad to make it have 8bits per charactor.

I added a spacer for readability

<?php
$str = 'Hello world';
$l = strlen($str);
$result = '';
while ($l--) {
    $result = str_pad(decbin(ord($str[$l])), 8, "0", STR_PAD_LEFT) . ' - ' . $result;
}
print $result;

//01001000 - 01100101 - 01101100 - 01101100 - 01101111 - 00100000 - 01110111 - 01101111 - 01110010 - 01101100 - 01100100
?>