Output from shell_exec() containing accent

2020-04-17 04:42发布

问题:

I've got a command which I'm running from PHP using shell_exec(). Sometimes the output of the command will contain accented characters.

When run from Bash, the output appears correctly. However, when run from shell_exec, the accented characters are lost and the output truncated somewhat.

Example output from Bash:

.                                   D        0  Tue Oct 25 16:45:26 2011
..                                  D        0  Tue Oct 25 16:45:26 2011

...

Background pres for political speech maggie & gemma.ppt      A  3323392  Fri Oct 24   14:31:26 2008
extra listening exercise on la télévision.doc      A    24064  Wed Jan 11 08:12:32 2006
gender of nouns.ppt                 A    42496  Fri Sep 10 07:55:42 2004

...

            63999 blocks of size 8388608. 36710 blocks available

Example output from shell_exec - note what happens to télévision, vidéo etc.:

.                                   D        0  Tue Oct 25 16:45:26 2011
..                                  D        0  Tue Oct 25 16:45:26 2011

...

Background pres for political speech maggie & gemma.ppt      A  3323392  Fri Oct 24 14:31:26 2008
extra listening exercise on la t  gender of nouns.ppt                 A    42496  Fri Sep 10 07:55:42 2004

...

    63999 blocks of size 8388608. 36710 blocks available

回答1:

The solution that worked for me was to run these commands before shell_exec, to make sure that the correct locale was being used:

$locale = 'en_GB.utf-8';
setlocale(LC_ALL, $locale);
putenv('LC_ALL='.$locale);

Presumably you can just change en_GB to whatever your language is. I noticed that the locale string seems to be case sensitive.