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

问题描述 投票:1回答:1

特殊要求: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
*
*

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

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

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

php shell utf-8 shell-exec hunspell
1个回答
4
投票

试试这段代码:

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

© www.soinside.com 2019 - 2024. All rights reserved.