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

Rory picture Rory · Jun 29, 2009 · Viewed 73.4k times · Source

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?

Answer

Stefan Gehrig picture Stefan Gehrig · Jun 29, 2009
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.