Current Location: Home> Latest Articles> How to Convert PHP String to Binary? Three Common Methods Explained

How to Convert PHP String to Binary? Three Common Methods Explained

gitbox 2025-06-25

How to Convert PHP String to Binary? Three Common Methods Explained

In PHP development, converting a string to binary is a common task. Whether it's for file handling, data encryption, or network transmission, binary formats play an important role. PHP provides various methods to convert strings to binary, and below we will introduce three common methods for this conversion.

Method 1: Using the pack Function

The pack function in PHP can be used to pack data into binary strings. By using different format specifiers, we can control the packing method. Here's an example of converting a string to binary:


$str = "Hello World";
$binary = pack('A*', $str);
echo bin2hex($binary);

In this example, the pack function is used with the 'A*' format specifier to convert the string into binary. Then, the bin2hex function converts it into hexadecimal format for output.

Method 2: Using ord Function and sprintf Function

If you need to convert the ASCII value of each character into binary, you can use the ord function to get the ASCII code of each character and then use the sprintf function to convert it into binary format. Here's how you can do it:


$str = "Hello World";
$binary = "";
for ($i = 0; $i < strlen($str); $i++) {
    $binary .= sprintf("%08b", ord($str[$i]));
}
echo $binary;

This method loops through each character in the string, gets its ASCII value, and then uses sprintf to convert these values into 8-bit binary strings. Finally, the binary strings are concatenated and printed.

Method 3: Using mb_ord Function and decbin Function

For strings containing non-ASCII characters (like Chinese), you can use mb_ord and decbin functions for the conversion. Here's an example for converting a string with Chinese characters:


function mb_str_to_binary($str) {
    $binary = "";
    $chars = mb_str_split($str);
    foreach ($chars as $char) {
        $binary .= decbin(mb_ord($char));
    }
    return $binary;
}
<p>$str = "你好,世界";<br>
$binary = mb_str_to_binary($str);<br>
echo $binary;<br>

This method first splits the string into an array of characters, then uses mb_ord to get the Unicode value of each character, and finally converts these Unicode values into binary format using decbin.

Summary

There are several methods to convert a string to binary in PHP. We've introduced three common methods: using the pack function, ord function with sprintf, and mb_ord with decbin. Depending on your needs, you can choose the most suitable method.

Regardless of the method you choose, the core idea is to loop through each character in the string and convert it to its corresponding binary representation. This makes it easier to handle, transmit, and encrypt the data as needed.