PHP exec change encoding

2019-01-24 03:58发布

问题:

I need to address UTF-8 filenames with the php exec command. The problem is that the php exec command does not seem to understand utf-8. I use something like this:

echo exec('locale charmap');

returns ANSI_X3.4-1968

looking at this SO question, the solution lookes like that:

echo exec('LANG=de_DE.utf8; locale charmap'); 

But I still get the same output: ANSI_X3.4-1968

On the other hand - if I execute this php command on the bash command line:

php -r "echo exec('LANG=de_DE.UTF8 locale charmap');"

The output is UTF-8. So the questions are:

  1. Why is there an different result be executing the php command at bash and at apache_module/web page?
  2. How to set UTF-8 for exec if it runs inside a website as apache module?

回答1:

To answer my own question - i found the following solution:

setting the locale environment variable with PHP

$locale='de_DE.UTF-8';
setlocale(LC_ALL,$locale);
putenv('LC_ALL='.$locale);
echo exec('locale charmap');

This sets to / returns UTF-8. So i'm able to pass special characters and umlauts to linux shell commands.



回答2:

I had the similar problem. My program was returning me some German letters like: üäöß. Here is my code:

$programResult = shell_exec('my script');

Variable $programResult is containing German umlauts, but they were badly encoded. In order to encode it properly you can call utf8_encode() function.

$programResult = shell_exec('my script');
$programResult = utf8_encode($programResult);