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 YOLOv5在进行trainpy训练后为什么会出现这种情况(语言-python)
  • ¥15 关于远程桌面的鼠标位置转换
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据
  • ¥15 为什么openeluer里面按不了python3呢?
  • ¥15 关于#matlab#的问题:训练序列与输入层维度不一样
  • ¥15 关于Ubuntu20.04.3LTS遇到的问题:在安装完CUDA驱动后,电脑会进入卡死的情况,但可以通过键盘按键进入安全重启,但重启完又会进入该情况!