cmdcharacter-encodingemojiwindows-terminalphp-7.0

Print emoji/foreign characters in CLI/shell/Terminal using PHP


When I run a script in the terminal containing <?php echo "🚀पीएचपी";, it displays garbage characters instead of the emoji and foreign text.

Specifically, it displays 🚀पीएचपी.

However, running a Node.js script containing console.log("🚀पीएचपी") correctly displays the emoji and the foreign text as 🚀पीएचपी.

How can I echo/print emojis and the foreign text properly so they display as intended in the CLI when using PHP?

Any suggestions on how to resolve this and get PHP to display emojis and unicode text correctly in the terminal?

This scenario has been tested using Windows Terminal (Powershell 7), cmd and GitBash(MINGW64) terminal

Running chcp in my windows terminal returns 65001 (which is utf-8). So the terminal itself is configured UTF-8 properly. Reference for chcp: https://learn.microsoft.com/en-us/windows/win32/intl/code-page-identifiers?redirectedfrom=MSDN

Minimal Reproducible Example:

  1. Run chcp 65001 in Windows Terminal/cmd.
  2. Run chcp again to make sure it returns Active code page: 65001.
  3. Run the php script below(make sure extension=mbstring is enabled in php.ini):
<?php

$utf8_string = "🚀पीएचपी";
$detected_encoding = mb_detect_encoding($utf8_string);

echo "Detected encoding[$utf8_string]: " . $detected_encoding;
  1. I still got this displayed:
Detected encoding[🚀पीएचपी]: UTF-8

ADDENDUM: I am using PHP7.0 . It works in PHP 8.2 but not PHP 7.0


Solution

  • shell_exec("chcp 65001");
    echo "Hello, 🚀पीएचपी";
    

    You have to definitely run shell_exec(chcp 65001) once before outputting emojis and foreign text. This answer has been tested with PHP7.0 using Windows Terminal and Powershell.

    sapi_windows_cp_set as related to sapi_windows_cp_get pointed out by @Oliver is only available PHP >=7.1.