Converting an emoji into an HTML entity with PHP

Published on 2023-10-10 • Modified on 2023-10-10

This snippet shows how to convert an emoji into an HTML entity with PHP. This is a way to do it. I'll explore other possible solutions in the following snippets.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet278Trait
{
    public function snippet278(): void
    {
        $emojis = ['🎶', '🖋', '🌈', '🐰', '⚙', '🔗'];

        foreach ($emojis as $emoji) {
            $utf32 = mb_convert_encoding($emoji, 'UTF-32', 'UTF-8');
            $hex4 = bin2hex($utf32);
            $dec = hexdec($hex4);
            echo $emoji.' => &#'.$dec.';'.PHP_EOL;
        }

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!