PHP通过proc_open调用Invoke-AI时含ō字符的命令执行失败
解决Windows 11下PHP 7.4调用Invoke-AI含特殊字符命令失败的问题
核心原因
Windows系统默认命令行编码(通常为GBK/936)与PHP执行子进程时的编码不匹配,导致含UTF-8特殊字符(如ō)的命令参数传递时乱码;而直接在终端执行时,终端已切换为UTF-8编码,因此能正常运行。
具体解决方案
1. 强制命令行环境使用UTF-8编码
在执行Invoke-AI命令前,先切换Windows代码页为UTF-8(代码页65001),确保命令参数能被正确解析:
$artist = "Baiōken Eishun"; // 用escapeshellarg包裹参数避免特殊字符解析错误 $escapedArtist = escapeshellarg($artist); // 拼接命令,先切换编码再执行Invoke-AI,>nul屏蔽chcp输出 $command = 'chcp 65001 >nul && invoke-ai --artist ' . $escapedArtist . ' [其他参数]'; exec($command, $output, $returnCode);
2. 显式统一PHP字符串编码
确保PHP处理的艺术家名称为UTF-8编码,避免隐式编码转换导致乱码:
$artist = "Baiōken Eishun"; // 检测并转换字符串为UTF-8 $utf8Artist = mb_convert_encoding($artist, 'UTF-8', mb_detect_encoding($artist)); $escapedArtist = escapeshellarg($utf8Artist); $command = 'chcp 65001 >nul && invoke-ai --artist ' . $escapedArtist . ' [其他参数]'; exec($command, $output, $returnCode);
3. 配置PHP默认编码
修改php.ini文件或在脚本开头设置,确保PHP内部使用UTF-8处理字符串:
// 脚本开头临时设置 ini_set('default_charset', 'UTF-8'); mb_internal_encoding('UTF-8'); mb_http_output('UTF-8');
修改php.ini后需重启PHP服务:
default_charset = "UTF-8" mbstring.internal_encoding = UTF-8
4. 用proc_open精细控制子进程环境
如果exec仍有问题,使用proc_open直接指定子进程的环境变量,确保Python(Invoke-AI依赖)使用UTF-8处理输入输出:
$descriptorspec = [ 0 => ["pipe", "r"], // 标准输入 1 => ["pipe", "w"], // 标准输出 2 => ["pipe", "w"] // 错误输出 ]; $env = [ 'CHCP' => '65001', 'PYTHONIOENCODING' => 'UTF-8' ]; $artist = "Baiōken Eishun"; $command = 'invoke-ai --artist ' . escapeshellarg($artist) . ' [其他参数]'; $process = proc_open($command, $descriptorspec, $pipes, null, $env); if (is_resource($process)) { fclose($pipes[0]); $output = stream_get_contents($pipes[1]); $error = stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); $returnCode = proc_close($process); }
5. 验证命令正确性
在PHP中输出拼接后的完整命令,复制到终端直接执行,确认是否能正常运行:
echo $command; // 输出后复制到终端测试
如果终端执行正常但PHP调用失败,说明问题出在PHP子进程的编码环境继承上,优先尝试方案1或4。
内容的提问来源于stack exchange,提问作者Blake
相关产品推荐
相关产品推荐

