1

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.

The text file looks like :

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>";
}
?>

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

Which would look something like:

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

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?

4

2 回答 2

2

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

<?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);
?>
于 2013-07-09T17:38:30.103 回答
1

好吧,这就是你可以做的......这是我自己的创作

function mydata($file_path,$start_line=0,$end_line=0)
{
$urldatafile = file($file_path) or die("Sorry, Couldn't load data!!");
if($end_line==0){
    $linecount = count($urldatafile);
    $end_line = $linecount;
}
$array_data = array_slice($urldatafile, $start_line, $end_line);
    echo "<table>";
    foreach ($array_data as $data)
    { 
    $data = explode("===", $data);

    echo "<tr>";
        echo "<td>{$data[0]}</td><td>{$data[1]}</td><td>{$data[2]}</td><td>{$data[3]}</td>";
    echo "</tr>"
    }
    echo "</table>";
}

在 example.txt 文件中,使用以下数据值写入每个新行

Data1===data2===data3===data4
Data1===data2===data3===data4
Data1===data2===data3===data4
Data1===data2===data3===data4
Data1===data2===data3===data4

用法:

mydata("PATH TO EXAMPLE TEXT FILE");

请注意 === 它将两个值分隔在一行中,还请注意,在文本文件中,新行应该是新行而不是自动换行。

于 2013-07-09T17:33:32.727 回答