gpt4 book ai didi

php - 将分解的文本文件转换为表格

转载 作者:行者123 更新时间:2023-11-29 06:05:20 25 4
gpt4 key购买 nike

我在 Linux 机器上运行 speedtest-cli,使用 Cron 作业定期运行它:

#!/bin/bash
date >> /home/blob/speedtest.log
/usr/local/bin/speedtest --simple >> /home/blob/speedtest.log

这会输出四个变量,每个变量之间有换行符:

Tue 31 Jan 20:00:01 UTC 2017
Ping: xx.xxx ms
Download: xx.xx Mbit/s
Upload: xx.xx Mbit/s

这些存储在一个连续的日志文件中。

我试图将它存储在五列中 - ID、日期、ping、下载、上传 - 数据库,这样我就可以运行 cron 作业,将结果读取到数据库,然后截断日志文件 (所以它没有重复):

<body>
<table>

<?php
$f = fopen("/home/blob/speedtest.log", "r") or exit("Unable to open file!");
$arr_to_insert = array();
// Read line by line until end of file
while (!feof($f)) {

// Make an array using line break as delimiter
$arrEx = explode('\n',fgets($f));
// Put exploded data in an array
echo '<tr><td name="date">' . $arrEx[0] . '</td><td name="ping">' . $arrEx[1] . '</td><td name="download">' . $arrEx[2] . '</td><td name="upload">' . $arrEx[3] . '</td></tr>';
//strore text file row to an array
$arr_to_insert[] = $arrEx;
}

fclose($f);
{

// Connect to Database
include '../includes/connection.php';
// Database Insert
foreach($arr_to_insert as $di){
$sql="INSERT INTO speed (date, ping, download, upload) VALUES ('{$di[0]}','{$di[1]}','{$di[2]}','{$di[3]}')";
if (!mysqli_query($conn,$sql))
{
die('Error: ' . mysqli_error());
}

}
mysqli_close($conn);
}
?>
</table>
</form>
</body>
</html>

它确实存储了数据 - 所以没有错误消息 - 但所有内容都在一列中,而不是每个 cron 作业都填充一行; date in date, ping in ping 等

ID  date    ping    download    upload
1 Sat 28 Jan
2 Ping: xx
3 Download: xx
4 Upload: xx
5 Sat 28 Jan
6 Ping: xx
7 Download: xx

有人可以指出为什么它在爆炸后没有填充表格,并且随后被正确地存储在数据库中。谢谢

最佳答案

日志文件包含以下内容:

Tue 31 Jan 20:00:01 UTC 2017

Ping: xx.xxx ms

Download: xx.xx Mbit/s

Upload: xx.xx Mbit/s

Tue 31 Jan 20:00:01 UTC 2017

Ping: xx.xxx ms

Download: xx.xx Mbit/s

Upload: xx.xx Mbit/s

它还在继续......所以每一行都有一条数据,每 4 行(日期、ping、下载、上传)是一个“组”。

在您的代码中,您有:

$arrEx = explode('\n',fgets($f)); 

fgets - returns a line.

所以你实际上在做:

1 轮循环:$arrEx = explode('\n', "Tue 31 Jan 20:00:01 UTC 2017");

2 轮循环:$arrEx = explode('\n', "Ping: xx.xxx ms");......

你应该做的是:

    $arr_to_insert = array();
$line = 1;
// Read line by line until end of file
while (!feof($f)) {
if($line == 1){
$group = array();
}

$group[] = fgets($f);


if($line == 4){
echo '<tr><td name="date">' . $group[0] . '</td><td name="ping">' . $group[1] . '</td><td name="download">' . $group[2] . '</td><td name="upload">' . $group[3] . '</td></tr>';

//reset lines group
$arr_to_insert[] = $group;
$line = 1;
unset($group);
} else {
$line++;
}
}

关于php - 将分解的文本文件转换为表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41981367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com