Run the shell_exec command with UTF-8 in PHP

1

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

Example:

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

Result:

How to print the above message with UTF-8?

    
asked by anonymous 10.04.2018 / 02:23

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 running a search and found that setlocale depends on the server configuration. If it does not 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 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

Setlocale Issues

    
10.04.2018 / 02:38