通过shell_exec使用utf-8文本输入来调用程序 [英] Call a program via shell_exec with utf-8 text input
本文介绍了通过shell_exec使用utf-8文本输入来调用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
权限:hunspell
和php5
.
bash的测试代码:
Test code from bash:
user@host ~/ $ echo 'sagadījās' | hunspell -d lv_LV,en_US
Hunspell 1.2.14
+ sagadīties
-正常工作.
测试代码(test.php):
Test code (test.php):
$encoding = "lv_LV.utf-8";
setlocale(LC_CTYPE, $encoding); // test
putenv('LANG='.$encoding); // and another test
$raw_response = shell_exec("LANG=$encoding; echo 'sagadījās' | hunspell -d lv_LV,en_US");
echo $raw_response;
返回
Hunspell 1.2.14
& sagad 5 0: tagad, sagad?ties, sagaudo, sagand?, sagar?o
*
*
屏幕截图(无法发布带有无效字符的代码):
Screenshot (could not post code with invalid characters):
似乎shell_exec无法正确处理utf-8,还是可能需要一些其他编码/解码?
It seems that shell_exec cannot handle utf-8 correctly, or maybe some additional encoding/decoding is needed?
编辑:我必须使用en_US.utf-8来获取有效数据.
EDIT: I had to use en_US.utf-8 to get valid data.
推荐答案
尝试以下代码:
<?php
// The word we are checking
$subject = 'sagadījās';
// We want file pointers for all 3 std streams
$descriptors = array (
0 => array("pipe", "r"), // STDIN
1 => array("pipe", "w"), // STDOUT
2 => array("pipe", "w") // STDERR
);
// An environment variable
$env = array(
'LANG' => 'lv_LV.utf-8'
);
// Try and start the process
if (!is_resource($process = proc_open('hunspell -d lv_LV,en_US', $descriptors, $pipes, NULL, $env))) {
die("Could not start Hunspell!");
}
// Put pipes into sensibly named variables
$stdIn = &$pipes[0];
$stdOut = &$pipes[1];
$stdErr = &$pipes[2];
unset($pipes);
// Write the data to the process and close the pipe
fwrite($stdIn, $subject);
fclose($stdIn);
// Display raw output
echo "STDOUT:\n";
while (!feof($stdOut)) echo fgets($stdOut);
fclose($stdOut);
// Display raw errors
echo "\n\nSTDERR:\n";
while (!feof($stdErr)) echo fgets($stdErr);
fclose($stdErr);
// Close the process pointer
proc_close($process);
?>
不要忘记验证文件的编码(以及因此传递的数据的编码)实际上是 UTF-8;-)
Don't forget to verify that the encoding of the file (and therefore the encoding of the data you are passing) actually is UTF-8 ;-)
这篇关于通过shell_exec使用utf-8文本输入来调用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文