
Example 6 - Reading From a FileThe previous example illustrated how to use PHP to read form data. In many cases you will also want to store the information submitted in a file or database. For example, if you are conducting an online survey you would want to write the survey results to a file so you an analyze them later. This example reads the output.txt created in the previous example and writes the information to the browser window.
<HTML>
<HEAD>
<TITLE> Example 6 </TITLE>
</HEAD>
<BODY>
<?
// the following statement opens the files called output.txt
// and reads each line of the file into an array called $readfile
// Each line will be accessed by it's position in the array
// $readfile[0] would be the first line because the array begins at 0
// rather than 1
$readfile = file("output.txt");
// Create a loop that will read all elements of the array and print out
// each field of the tab-delimited text file
for ($k=0; $k<=count($readfile)-1; $k++) {
$fields = split("\t",$readfile[$k]);
print("$fields[0] $fields[2]<br>");
}
?>
</BODY>
</HTML>
There are several functions used to read data in PHP. This example uses the Next, the Example uses a
for ($var=start value; $var< stop value; increment) {
statements to perform;
}
The Within the loop the PHP Finally, the Note for UT Austin Web Central Users: Because Web Central runs PHP in safe mode, the file that you read from must be owned by the same user that owns the PHP script. If you have questions about this, we suggest making an appointment with a Teamweb consultant. Simple SearchExample 6 can easily be modified to search for a particular record in a file rather than simply displaying all records. Add a conditional statement within the for loop to check if the field that was just read matches some condition, for example a search string entered in a form.
for ($k=0; $k<=count($readfile)-1; $k++) {
$fields = split("\t",$readfile[$k]);
// if the name field equals the name field entered in a search form
// print that record and exit the loop
if ($fields[0] == htmlentities($_POST[searchname])) {
print("$fields[0] and $fields[2]<br>");
exit;
}
}
Test this search example PHP Manual Pages |