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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!