An alternative in php to the xxd command in linux

526 Views Asked by At

I need to convert the bin file to a string in PHP in the same way as the Linux program does.

In linux: xxd -g 1 data.bin and output: 0000000: 02 50 45 10 02 06 54 62 43 20 05 20 11 07 21 12 .PE...TbC . ..!.

In PHP, I tried to use the bin2hex function, but i get only the digits 02 50 45 10 02 06 54 62 43 20 05 20 11 07 21 12. I also need an offset and textual representation.

The offset is the line number, the first digits and a colon (0000000:) in the string I entered above. This is actually not a problem, because I can write code that calculates this, but the bigger problem is with textual representation (.PE...TbC . ..!.).

Someone can help? What functions could I use for this?

1

There are 1 best solutions below

0
On

You can use a regular expression to replace non-printable characters with a . (or whatever character you choose).

$data = hex2bin('02504510020654624320052011072112');
$text_representation = preg_replace('/[^[:print:]]/', '.', $data);
var_dump($text_representation);