fgets 的输出与文件格式不匹配

Output of fgets does not match formatting of file

我尝试将 linux 命令 ifconfig 的输出保存到一个变量中,并在我的 html 中显示它。我有两个页面,一个 test.html 和一个 ajax.php。如果我在 test.html 上单击 link,然后向 ajax.php 发出 ajax 请求,执行 ifconfig 并将结果发送回 test.html,整个正文标签的 html 被替换为输出。

我的 ajax.php 中有此代码。如您所见,我将 ifconfig 的输出写入文件,因此我可以从文件流中读取每一行并输出它们。

shell_exec ("/sbin/ifconfig > /tmp/ifconfig 2>&1");
$ifconfig = fopen("/tmp/ifconfig","r") or die ("Unable to open file '/tmp/ifconfig'"); 

while(!feof($ifconfig))
{     
    echo fgets($ifconfig). "<br>";     
}

fclose($ifconfig);

但不是这样的输出:

 eth0      Link encap:Ethernet  HWaddr 0A:58:C2:71:7A:90  
           inet addr:172.15.47.121  Bcast:172.25.255.255  Mask:255.255.0.0
           UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
           RX packets:238319 errors:0 dropped:0 overruns:0 frame:0
           TX packets:122439 errors:0 dropped:0 overruns:0 carrier:0
           collisions:0 txqueuelen:1000 
           RX bytes:21355179 (20.3 MiB)  TX bytes:19679738 (18.7 MiB)

我得到这个输出:

eth0 Link encap:Ethernet HWaddr 0A:58:C2:71:7A:905
inet addr:172.15.47.121 Bcast:172.15.255.223 Mask:255.255.0.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:23405 errors:0 dropped:14 overruns:0 frame:0
TX packets:16390 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1613474 (1.5 MiB) TX bytes:19949404 (19.0 MiB)

谁能告诉我如何获得与实际格式相同的输出? 注意:地址不是真实的,我更改了它们。

如果您的输出应该用于网站,只需将其包装到 <pre></pre> 标签中:

echo "<pre>";
while(!feof($ifconfig))
{
    echo fgets($ifconfig). "<br>";
}
echo "</pre>";

pre标签中,大多数浏览器使用monospace作为字体,所以它看起来更像是直接控制台输出。

输出被破坏,因为在 html 页面中空格的处理方式非常不同(虽然它们在这里,但不会呈现,请查看您的页面源代码)。

您可能对应用于父 html 标签以更改此行为的 CSS 属性 white-space 感兴趣:

<body style="white-space:pre-wrap">
Your php here
</body>