Run shell_exec with UTF-8 in PHP

Asked

Viewed 257 times

1

I am developing a system in PHP language and use the command shell_exec, but when I return some message with accentuation, it does not show the character.

Example:

Commando: <?=shell_exec('tasklist /fi "pid eq '.getmypid().'" ')?>

Upshot:

inserir a descrição da imagem aqui

How to print the above message with UTF-8 ?

1 answer

2


You can use the setlocale to do this. This way:

$locale = 'pt_BR.UTF-8';
setlocale(LC_ALL, $locale); // LC_ALL informa que tudo abaixo deste código será configurado para pt_BR.UTF-8
putenv('LC_ALL='.$locale);    
shell_exec('tasklist /fi "pid eq '.getmypid().'" ');

Edit

I’ve been doing some research and discovered that the setlocale depends on the server configuration. If it doesn’t work with pt_BR, try using en_US, which is the default for many servers.

You can also use variations, like this:

setlocale(LC_ALL, 'en_US.UTF-8', 'en_US.UTF8', 'en.UTF-8', 'en.UTF8');

Edit 2

Another option is to use the utf8_encode:

$saida = shell_exec('tasklist /fi "pid eq '.getmypid().'" ');
$saida = utf8_encode($saida);
echo $saida;

Try this way too:

$saida = shell_exec('tasklist /fi "pid eq '.getmypid().'" ');
$saida = utf8_encode($saida);

foreach(mb_list_encodings() as $chr){ 
       $saida = mb_convert_encoding($saida, 'UTF-8', $chr);    
} 

References:

Stackoverflow

Problems with setlocale

  • I made these changes that you commented and did not work, did not return me in UTF-8 the message. It continues to be displayed the same way

  • @Piupz has another option.

  • @Piupz try with Edit 2

  • He called me back thus, is not yet in UTF-8 =/

  • @Piupz ok! The problem is that the server is not set to utf8. I will see if I can do something about it.

  • @Piupz take a look at the issue and see if it resolves now.

  • 1

    You have to change the shell locale, not PHP locale. Or else, simply take the shell result and convert into the view, which is much simpler (which is practically the end of the answer). Now, first of all is missing in the question something confirming the current shell locale.

  • @Bacchus is right. I think a echo setlocale(LC_ALL, 0); shows which location is.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.