Create table from text file using PHP [closed]

有些话、适合烂在心里 提交于 2019-12-26 10:45:28

问题


I need to create a table with borders from the text file (this text file is updated every time when someone finishes filling a form. One row, one person):

Herard|TRO789|Suzuki|France|Gendolfina|Fresko|food|500|2015-04-25 14:40
Bob|MGA789|Mercedes|Latvia|Polaris|Dread|parts|1000|2015-04-26 16:15

I've already created a script which reads every word separately, but don't know how to to put them to table:

<?php
$file = fopen("info.txt", "r") or die("Unable to open file!");
while (!feof($file)){   
    $data = fgets($file); 
    list($name, $number, $type, $country, $company, $gcompany, $supply, $weight, $datetime) = explode("|", $data);
    }
    fclose($failas);
?>

So I need a script which could read the text file and create a table with the same number of rows as the text file has.


回答1:


Use str_replace to replace the | signs with HTML table cell delimiters.

<?php
echo '<table border="1">';
$file = fopen("info.txt", "r") or die("Unable to open file!");
while (!feof($file)){   
    $data = fgets($file); 
    echo "<tr><td>" . str_replace('|','</td><td>',$data) . '</td></tr>';
}
echo '</table>';
fclose($file);
?>



回答2:


This solution is not clean but works. you can also use explode to create an array instead of many variables:

<table>   
    <?php
        $file = fopen("info.txt", "r") or die("Unable to open file!");
        while (!feof($file)){   
            $data = fgets($file); 
            list($name, $number, $type, $country, $company, $gcompany, $supply, $weight, $datetime) = explode("|", $data);
    ?> 
    <tr>
        <td><?=$name ?></td>
        <td><?=$number ?></td>
        ...
    </tr>
    <?php
        }
        fclose($failas);
   ?>
</table>


来源:https://stackoverflow.com/questions/29867025/create-table-from-text-file-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!