php - 使用 utf-8 文本输入通过 shell_exec 调用程序

标签 php shell utf-8 shell-exec hunspell

先决条件:hunspellphp5

从 bash 测试代码:

user@host ~/ $ echo 'sagadījās' | hunspell -d lv_LV,en_US
Hunspell 1.2.14
+ sagadīties

- 工作正常。

测试代码(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
*
*

屏幕截图(无法发布包含无效字符的代码): Hunspell php invalid characters

shell_exec 似乎无法正确处理 utf-8,或者可能需要一些额外的编码/解码?

编辑:我必须使用 en_US.utf-8 来获取有效数据。

最佳答案

试试这个代码:

<?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;-)

关于php - 使用 utf-8 文本输入通过 shell_exec 调用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10028925/

相关文章:

swift - 将 ASCII 符号插入字符串 (Swift)

JavaScript DOM XSS 注入(inject)验证

php - 将一个长页面拆分为多个页面

javascript - 在nwjs中使用shelljs执行命令?

shell - 如何从shell脚本中的变量中删除回车符

c++ - 检查 char* 缓冲区是否包含 UTF8 字符?

php - 无法从 laravel 中的相关表中获取详细信息(使用 with)

php - 安全密码存储

php - 如何评价或排名选票

python - 如何在此脚本中找到查找结果以通过电子邮件发送