Search code examples
phparraysloopsunicodeemoji

PHP Foreach Loop to Print All Emojis


I see that there's better support of Emojis in PHP 7 but no packaged set/library of emojis to reference from. As of now, I have to search and look for the UNICODE of the emoji I desire at https://apps.timwhitlock.info/emoji/tables/unicode.

Would there be an easier method to obtain every single (latest) Emoji by iterating through a loop rather than referencing an array I would have to build on my own (copying & pasting every UNICODE)?


Solution

  • Try the following:

    <?php
    
    $data = file_get_contents("https://apps.timwhitlock.info/emoji/tables/unicode");
    
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);
    $doc->loadHTML($data);
    libxml_clear_errors();
    $finder = new DomXPath($doc);
    $nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' code ')]");
    $unicodes = [];
    $i = 1;
    foreach ($nodes as $node) 
    {
    if($i % 2 === 0) {$i++;continue;}
    
        $unicode = trim($node->textContent);
        $unicodes[] = $unicode;
        file_put_contents("unicodes.txt", $unicode. "\r\n", FILE_APPEND);
    
        $i++;
    }
    
    var_dump($unicodes);
    

    It will take all the Unicodes from the site and store it in a file unicodes.txt and in array $unicodes. This simply uses DOMDocument to scrap the page. And Then you can get all of them using:

    <?php
    
    $emojis = file("unicodes.txt");
    
    foreach($emojis as $emoji)
    {
        $emoji = trim($emoji);
        $emoji = hexdec($emoji);
        echo "&#$emoji;";
    }