从文本文件中读取数据并使用php形成表格 [英] Reading data from text file and forming a table using php

查看:252
本文介绍了从文本文件中读取数据并使用php形成表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含看起来像在表格中格式化的数据。但它们只是有序的文字行,类似于一张桌子。我正在尝试读取文本文件,只获取一些数据并形成一个HTML表格。

I have a text file that contains data that looks like being formatted in a table. But they are just ordered lines of text made to resemble a table. I am trying to read the text file, get only some of data and form a HTML table.

文本文件如下所示:

Class 1:
S.No RollNumber Name RandomAllocatedNumber Overall Result
---- ---------- ---- --------------------- --------------
1 ABC-BYT-M56-8T Sam Jackson NBV26173GHS Pass
2 BNS-SUD-H72-7Y Mario Javi  HAS12824SAD Pass

Class 2:
S.No RollNumber Name RandomAllocatedNumber Overall Result
---- ---------- ---- --------------------- --------------
1 POW-AVE-S36-7C Matt Stepson GSA22343GFS Pass
2 EWG-JAS-T12-3R Taylor Xavier  EWF54524EAD Pass

我使用此代码读取完整文件并显示输出:

I used this code to read the complete file and display the output:

<?php
foreach(glob(somefile.txt") as $filename) {
$file = $filename;
$contents = file($file);
$string = implode("<br>",$contents);
echo $string;
echo "<br></br>";
}
?>

但是我需要从上面的数据中只获得学号,滚动号和RandomAllocatedNumber。

But I need to get only Student number, roll number and RandomAllocatedNumber from the above data.

这看起来像:

ClassNo |RollNumber     |RandomAllocatedNumber

1       |ABC-BYT-M56-8T |NBV26173GHS
1       |BNS-SUD-H72-7Y |HAS12824SAD
2       |POW-AVE-S36-7C |GSA22343GFS
2       |EWG-JAS-T12-3R |EWF54524EAD

上表是我希望显示的内容在php页面中,而不是完全阅读行并显示整个文件。

The above table is what I look to be displayed in the php page rather than totally reading the lines and displaying the whole file.

如何更改我的简单代码才能获得此代码?

How can I change my simple code to get this?

推荐答案

使用该输入格式,这应该产生您要求的输出:

With that input format, this should produce the output you asked for:

<?php
$file = fopen("somefile.txt",'r');
$class = 0;
while (!feof($file))
{
    $line = trim(fgets($file));
    if ($line)
    {
        if (strlen($line)==8 && substr($line, 0, 5)=="Class") $class = $line[6];
        elseif (is_numeric($line[0]))
        {
            $parts = explode(" ",$line);
            echo $class." | ".$parts[1]." | ".$parts[count($parts)-2]."<br>";
        }
    }
}
fclose($file);
?>

这篇关于从文本文件中读取数据并使用php形成表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆