Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Emoji from Unicode in PHP?

Tags:

php

unicode

emoji

I use this table of Emoji and try this code:

<?php print json_decode('"\u2600"'); // This convert to ☀ (black sun with rays) ?> 

If I try to convert this \u1F600 (grinning face) through json_decode, I see this symbol — ὠ0.

Whats wrong? How to get right Emoji?

like image 670
Platon Avatar asked Nov 05 '15 14:11

Platon


People also ask

How to convert emoji to unicode in PHP?

php function emoji_to_unicode($emoji) { $emoji = mb_convert_encoding($emoji, 'UTF-32', 'UTF-8'); $unicode = strtoupper(preg_replace("/^[0]+/","U+",bin2hex($emoji))); return $unicode; } $var = "😀"; echo emoji_to_unicode($var); ?> Show activity on this post.


1 Answers

PHP 5

JSON's \u can only handle one UTF-16 code unit at a time, so you need to write the surrogate pair instead. For U+1F600 this is \uD83D\uDE00, which works:

echo json_decode('"\uD83D\uDE00"'); 😀 

PHP 7

You now no longer need to use json_decode and can just use the \u and the unicode literal:

echo "\u{1F30F}"; 🌏 
like image 171
Tino Didriksen Avatar answered Oct 13 '22 10:10

Tino Didriksen