How to read txt file into Html Table

Read content or data from text file and write it into HTML Table

codingzon-readTxttoHtml

 

 

This tutorial explains How to read the contents of a text file and write it into an HTML table using PHP Scripting.

Below, there are two files : 

1. states.txt: All the data is separated with semicolon(;). Create states.txt and copy below content and save it in a project folder.

2. demo.php: Reads the sates.txt file, displays the data in a table. Create it and save in the same project folder. Start server and open it in a browser. You can see the output as shown in the image down below.

 

The content of the text file is as follows:

states.txt

1;Alabama;Montgomery;5,024,279
2;Alaska;Juneau;733,391
3;Arizona;Phoenix;7,151,502
4;Arkansas;Little Rock;3,011,524
5;California;Sacramento;LosAngeles;3,914,4818

 

MOVETOP↑

 

 Code explanation:

1. for each loop, reads each row from the file
2. explode function takes two parameters
3. The first one is the character you want to separate(delimiter),
and the second is the string you want to separate.
4. In this is case, the first parameter is ';' and the second parameter is $row.
It splits the $row into words and puts it in a State array.
5. Another for each loop, inside the above for each, reads each element($col) from $state array and displays in a table.

 

demo.php
 
 
<html> 
<head>
<title>Codingzon tutorials</title>
</head> 
<body>
 
<table width="200" border="1">
    <tr>
        <td>StateID</td>
        <td>StateName</td>
        <td>Capital</td>
        <td>Population</td>
    </tr>
 
<?php 
 
$state = array();

$file = file('states.txt');

foreach($file as $row){  // reads eachline from the file and copies into $row
 
$state= explode(';', $row); // explode function takes delimiter(;),array i.e $row and splits it, and copies into Sstate array
 
echo '<tr>';
	foreach($state as $col){ // internal foreach reads each column from the state and displays in a '<td>'
	 
	echo'<td>'.$col.'</td>';
	}
echo '</tr>';
 }
?> 
 
</table>
 
</body>  
</html>
 
Result:
 
 


 

 

 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP