it_is_a_literature it_is_a_literature - 3 months ago 19
PHP Question

How to display file into binary format with php?

To create a new file ,to input just one enter key and save it as test.txt.

There is only one '\n' in the test.txt.

To display the file with command:

xxd -b ./test.txt
0000000: 00001010


Now i want to do the same job with php.

<?php
function parse($target){
$file_handle = fopen($target, "rb");
while (!feof($file_handle)) {
$byte = fread($file_handle,1);
echo base_convert(ord($byte),10,2);
}
fclose($file_handle );
}
parse('test.txt');
?>


The result is 10100 ,how to fix my php code to get the such right answer 00001010 as xxd -b ./test.txt ?

Think to Pyton's code.

<?php
function parse($target){
$file_handle = fopen($target, "rb");
while (!feof($file_handle)) {
$byte = fread($file_handle,1);
echo sprintf("%08s ",base_convert(ord($byte), 10, 2));
}
fclose($file_handle );
}
$target='test.txt';
echo filesize($target);
parse($target);
?>


The filesize is 1,but result is
00001010 00000000
,how to make it to be exactly
00001010
?

Answer
<?php
function  parse($target){
    $file_handle = fopen($target, "rb");
    $filesize = filesize($target);    
    while (!feof($file_handle)) {
        $byte = fread($file_handle, 1);
        echo sprintf("%'08b", ord($byte));
        if(ftell($file_handle) == $filesize) {
            break;
        }
    }
    fclose($file_handle );
}
parse('test.txt');

Output:

00001010