doumei4964 2019-07-31 09:37
浏览 52
已采纳

在PHP的popen中格式化输出bash脚本

In my PHP script I'm executing a bash script with popen() and I output the response. But the response has a different encoding, and I don't know how to convert it.

I tried to convert it to utf8 but no results. Also tried to set the locale to nl_NL.utf8.

PHP function:

while (@ ob_end_flush()); // end all output buffers if any

$proc = popen("$cmd 2>&1 ; echo Exit status : $?", 'r');

$live_output     = "";
$complete_output = "";

while (!feof($proc))
{
    $live_output     = fread($proc, 4096);
    $complete_output = $complete_output . $live_output;
    echo "$live_output";
    @ flush();
}

pclose($proc);

Example response:

[2K[1A[2K[G
[2K[1A[2K[G⠋ load plugins
[2K[1A[2K[Gsuccess load plugins - 0.975 s
⠋ load plugins

This should be just:

success load plugins - 0.975 s

The ⠋ thing is a loader which is moving. Could that be the problem? Or are these characters the colorcode of the line?

  • 写回答

1条回答 默认 最新

  • dpthuyh1678 2019-08-01 14:26
    关注

    Those are ANSI Escape Sequences, they are not bash commands but console commands used for coloring output or replacing/updating output on a single line.

    Often commands offer a —no-color flag.

    Also, a environment variable exists for common commands: NO_COLOR. Here's a list of common flags/variables to disable colored output => https://no-color.org/

    Otherwise, you could always filter the output with a regex: /(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料