Symfony 控制台组件 - 输出问题和表格时出错

问题描述

我正在使用 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

有人知道我如何解决这个问题吗?

解决方法

在调用 @sapi_windows_cp_set(65001); 方法之前(或之后)调用 ask。 (@ 只是为了抑制任何错误。):

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,(仅在 Windows 上)并且该代码页与操作系统的当前代码页不匹配。

为什么是 65001?

did sapi_windows_cp_get() 获取操作系统的当前代码页。此外,根据 Windows here,代码页 65001 适用于 UTF-8。

另见问题 here

请注意,即使代码页 65001 应该呈现 UTF-8 字符,但如果您希望用户在响应 {{1 }} 方法。您需要为此使用代码页 1252

上面 Symfony 代码的来源是 this commit。 (另请参阅该提交的 conversation

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...