How to read txt file into Html Dropdown
Read content/data from text file and write it into HTML Dropdown
This blog demonstrates how to populate a dropdown list with values from a text file using PHP.
This tutorial uses two files.
1. states.txt:
The text file contains a set of rows. Each row contains a state information such as stateID, stateName, stateCapital, statePopulation etc. and each value in a row, separated with semicolon. Other variations are possible to store states info ex: CSV, but in this tutorial our goal is reading a text file and populating data in an HTML dropdown. The first line in the states.txt file contains the columns names. The next five rows are the data. As shown below, link.
2. demo1.php: Displays text data in a dropdown.
There are 3 steps implemented in this file
step1- Reads the sates text file and stores states details in an array.
step2- There is an HTML form with one dropdown. All array data is loaded in a dropdown using foreach loop.
step-3- User selects the state from the dropdown and summits. Submitted value ( state ID ) passed to demo2.php.demo2.php- displays the state information.
demo1.php
<html>
<head> <title>Codingzon tutorials</title> </head>
<body bgcolor=""> <center> <br /><br /><br /><br /> <?php $stateID = array(); $statename = array();
$filename = 'states.txt'; $file = file($filename,FILE_IGNORE_NEW_LINES); foreach($file as $row){ $cols= explode(',', $row); array_push($stateID,$cols[0]); $statename[] = $cols[1]; } $len = sizeof($stateID); ?> <form action="demo2.php" method="POST"> Select State Name: <select name="stateID"> <?php for($i=0 ; $i<$len ;$i++){ echo '<option value="'.$stateID[$i].'">'. $statename[$i]. '</option>'; } ?> </select> <input type="submit" name="submit" value="Go" /> </form> </center> </body> </html>
Result:
Note:demo2.php explained in a coming tutorial
Comments
Post a Comment