PHP string → hex means: take the string’s bytes and render each byte as two hex digits. The primary tool is bin2hex(). Encoding only matters when you must change the byte layout before hexing (for example UTF-8 → GBK).
Pair with the reverse guide PHP hex to string. Online: String to Hex.
bin2hex basics
<?php
echo bin2hex('Hello'); // 48656c6c6f
echo bin2hex('你好'); // e4bda0e5a5bd (UTF-8 bytes)
$bytes = hex2bin('48656c6c6f');
echo $bytes; // Hello
bin2hex does not “encode to UTF-8.” It hex-encodes whatever bytes are already in the string.
When to convert encoding first
<?php
$utf8 = '你好';
$gbk = mb_convert_encoding($utf8, 'GBK', 'UTF-8');
echo bin2hex($gbk); // different hex than UTF-8
Use this only for legacy wire formats. Modern APIs should keep UTF-8 end-to-end.
pack alternative
<?php
echo unpack('H*', 'Hello')[1]; // 48656c6c6f
Prefer bin2hex for readability unless neighboring code already uses pack/unpack. More: PHP pack().
Practical tips
- Hex doubles size — do not store every database field as hex; use binary columns for blobs.
- For URLs, prefer proper percent-encoding over ad-hoc hex unless a protocol requires hex.
- Hashes (
hash('sha256', $data)) already return hex; do notbin2hexthem again.
<?php
echo hash('sha256', 'test'); // already hex
Related: hex2bin() · hex encoding overview.