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:
- Run
chcp 65001
in Windows Terminal/cmd. - Run
chcp
again to make sure it returnsActive code page: 65001
. - 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;
- I still got this displayed:
Detected encoding[🚀पीएचपी]: UTF-8
2
Answers
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.
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 :
then in the
php.ini
, enable thembstring
extension like belowyou mentioned that running
chcp
returns65001
,which is theUTF-8
code page, and it suggests that your terminal is configured, but if you are usingGit Bash
, you may need to set theLANG
environment variable toen_US.UTF-8
by running this in your terminal: