我正在使用Symfony控制台组件编写一个控制台应用程序。我正在尝试与问题和表格互动。我想问一个问题,然后输出一个表,然后问另一个问题并输出另一个表。所有这些都发生在同一个命令类中。这是我的代码:
protected function interact( InputInterface $input, OutputInterface $output ) {
$this->input = $input;
$this->output = $output;
$question_helper = $this->getHelper( 'question' );
$question = ( new ConfirmationQuestion( 'This is a confirmation question:' ) );
$question_result = $question_helper->ask( $this->input, $this->output, $question );
$table = new Table( $this->output );
$table
->setHeaders( array( 'Name', 'Age' ) )
->setRows(
array(
array( 'Mike', 21 ),
array( 'Sara', 22 ),
)
);
$table->setStyle( 'box' );
$table->render();
}
当我试图实现我的代码时,这个问题很有效,但当我输出表时,它以一种奇怪的方式显示,如下所示:
This is a confirmation question: bla bla
┌──────┬─────└‚ Name │ Age │
├──────┼─────┤
│ Mike │ 21 │
│ Sara │ 22 │
└──────┴─────┘
如果我在问题之前重复表格,它会起作用:
┌──────┬─────┐
│ Name │ Age │
├──────┼─────┤
│ Mike │ 21 │
│ Sara │ 22 │
└──────┴─────┘
This is a confirmation question: bla bla
有人知道我该怎么解决这个问题吗?
在调用ask
方法之前(或之后(调用@sapi_windows_cp_set(65001);
。(@
只是为了抑制任何错误。(:
if (function_exists('sapi_windows_cp_set')) {
@sapi_windows_cp_set(65001);
}
问题是,Symfony在控制台收到问题的回复时强制其使用代码页1252:
if (function_exists('sapi_windows_cp_set')) {
// Codepage used by cmd.exe on Windows to allow special characters (éàüñ).
@sapi_windows_cp_set(1252);
}
因此将代码页设置为1252
(仅在窗口上(并且该代码页与OS的当前代码页不匹配。
为什么选择65001
执行sapi_windows_cp_get()
以获取操作系统的当前代码页。根据这里的Windows,代码页65001是UTF-8的。
另请参阅此处的问题。
请注意,即使代码页65001应该呈现UTF-8字符,但如果您希望用户在对ask
方法的响应中输入特殊字符(éuüñ等(,它也无法正常工作。您需要使用代码页1252进行
上面Symfony代码的来源就是这个提交。(另请参阅提交的对话(