skip to Main Content

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

2

Answers


  1. The issue you’re seeing might be related to the terminal’s encoding settings, rather than PHP itself. Your terminal needs to support and be set to use UTF-8 to correctly display the emoji and foreign text. The mb_detect_encoding function is detecting the encoding of the string as UTF-8, which is correct.

    To verify that PHP is correctly handling the UTF-8 encoded string, you could write the string to a file and then open that file in a text editor that you know supports UTF-8. If the text displays correctly in the text editor, then PHP is handling the UTF-8 encoding correctly, and the issue is likely with your terminal’s settings.

    Login or Signup to reply.
  2. I think you need to make sure that the terminal and PHP and your script itself are all configured to handle UTF-8 encoding correctly,so first of all add this two lines to your script :

    mb_internal_encoding("UTF-8");
    mb_http_output("UTF-8");
    

    then in the php.ini, enable the mbstring extension like below

    extension=mbstring
    

    you mentioned that running chcp returns 65001,which is the UTF-8 code page, and it suggests that your terminal is configured, but if you are using Git Bash, you may need to set the LANG environment variable to en_US.UTF-8 by running this in your terminal:

    export LANG=en_US.UTF-8
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search