试图获取CPU使用情况时出现语法错误



我想使用shell_exec获取CPU的使用情况,但我遇到语法错误,这是我的代码:

$cpu_usage = " top -bn1 | grep "Cpu(s)" | sed "s/.*, *([0-9.]*)%* id.*/1/" | awk '{print 100 - $1"%"}' ";
shell_exec($cpu_usage);

错误:

语法错误,意外的's'(T_STRING(

您收到此错误消息是因为您(无意中(过早终止了字符串:

$cpu_usage = " top -bn1 | grep "Cpu(s)" | sed "s/.*, *([0-9.]*)%* id.*/1/" | awk '{print 100 - $1"%"}' ";
//                             ^ PHP sees this as the end of the string

解决这个问题最简单的方法是使用nowdoc字符串表示法,因为它不在字符串内部进行任何解析:

Nowdocs对单引号字符串的作用就像heredocs对双引号字符串的影响一样。nowdoc的指定类似于heredoc,,但在nowdoc内部不进行解析。该构造非常适合嵌入PHP代码或其他大块文本,而无需转义

(强调矿(

$cpu_usage = <<<'STR'
top -bn1 | grep "Cpu(s)" | sed "s/.*, *([0-9.]*)%* id.*/1/" | awk '{print 100 - $1"%"}'
STR;
shell_exec($cpu_usage);

最新更新