How can I get a hex dump of a string in PHP?

Viewed 82237

I'm investigating encodings in PHP5. Is there some way to get a raw hex dump of a string? i.e. a hex representation of each of the bytes (not characters) in a string?

6 Answers
echo bin2hex($string);

or:

for ($i = 0; $i < strlen($string); $i++) {
    echo str_pad(dechex(ord($string[$i])), 2, '0', STR_PAD_LEFT);
}

$string is the variable which contains input.

    echo implode(array_map(
        fn ($a, $b) => sprintf("%-26s%-8s\n", $a, $b), 
        str_split(implode(' ', str_split(bin2hex($string), 2)), 24),
        str_split($string, 8)
    ));
Related