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-?]*[ -\/]*[@-~]/

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵