Php exec () in Unicode mode?

I need to execute command line commands and tools that accept ut8 as input or generate ut8 output. So I use cmd and it works, but when I try to do it from php with exec, it does not work. To make it simple, I tried a simple output redirection.

When I write directly on the command line:

chcp 65001> nul && echo cschschschuya-öüäß> utf8.txt

The uft8.txt file is created correctly.

tscshshchuya-öüäß

When I use the exec function from php:

$cmd = "chcp 65001 > nul && echo -öüäß>utf8.txt"; exec($cmd,$output,$return); var_dump($cmd,$output,$return); 

contents in utf8.txt are mixed up:

¥ Å ¥ Î ¥ ^ ¥% ¥ Z ¥? -ÇôǬÇÏÇY

I am using Win7.64bit with (Console) Codepage 850.

What should I do to fix this?

Additional Information: I am trying to overcome some problems with reading and writing utf8 file names in windows. PHP file functions cannot be executed: glob, scandir, file_exists cannot correctly process utf8 file names. The file is invisible, skipped, names changed ... so I want to avoid php files, and I'm looking for some php extern filehandling.

+6
source share
1 answer

Since I could not find an easy, fast and reliable internal php solution, I end up knowing that it works. CMD-batch file. I am making a small function that generates a cmd batch file at runtime. It just adds the chcp (change the codepage) command to switch to unicode. And analyze the output.

 function uft8_exec($cmd,&$output=null,&$return=null) { //get current work directory $cd = getcwd(); // on multilines commands the line should be ended with "\r\n" // otherwise if unicode text is there, parsing errors may occur $cmd = "@echo off @chcp 65001 > nul @cd \"$cd\" ".$cmd; //create a temporary cmd-batch-file //need to be extended with unique generic tempnames $tempfile = 'php_exec.bat'; file_put_contents($tempfile,$cmd); //execute the batch exec("start /b ".$tempfile,$output,$return); // get rid of the last two lin of the output: an empty and a prompt array_pop($output); array_pop($output); //if only one line output, return only the extracted value if(count($output) == 1) { $output = $output[0]; } //delete the batch-tempfile unlink($tempfile); return $output; } 

Usage: just like php exec ():

utf8_exec ('echo valid-öüäß> utf8.txt');

OR

uft8_exec ('echo valid-öüäß', $ output, $ return);

+9
source

All Articles