How to enter a multibyte Unicode string in PHP

This has just taken me a suprisingly long time to work out ...

I needed to output a file with the follwing as a marker in various places.

♦ U+2666 BLACK DIAMOND SUIT

General Character Properties

Unicode category: Symbol, Other

Various Useful Representations

UTF-8: 0xE2 0x99 0xA6
UTF-16: 0x2666

C octal escaped UTF-8: \342\231\246
XML decimal entity: ♦

OK so I know the hex code I think I'll just use chr() but no... this only works for ASCII...

...and the mbstring functions are great for working with multi-byte strings but don't help enter them

It turns out that you can either copy a literal ♦ into your source code - or use the pack() function

<?php
header
('Content-Type: text/plain;charset=utf-8');
echo
"♦\n";

echo
pack("ccc", 0xE2, 0x99, 0xA6) ."\n";


?>

Tags

Comments

I ran into the same issue

I ran into the same issue and this hint saved me hours. The PHP pack() function is not explained very well for those who haven't had to bother with binary strings and don't have a Perl background with the pack() function - you'll see numerous references to Perl in the documentation for pack()

Post new comment

Got something to add - just enter a comment
all other fields are optional.

Your email address will not be published.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
10 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.