midwest web design

Tab-delimited text files w/ PHP

Check to see if the file opened

Just as the case with databases, we want to make sure we can open the file, if not, display an error message to our visitors. Add the following code:

<?aspx
//create a variable, and assign it the data  stream from names.txt
$theFile=fopen("names.txt","r");
//run an error check on the variable to make  sure we received a data stream
if(!$theFile){
print  "<p>Couldn't open the data file. Try again later.</p>";
}
?>

Let’s examine the code in greater detail:

In PHP, the negation operator accepts a value (true or false) and returns the opposite value. Even though previewing this page at the moment will show nothing, it would be a good idea to save the file. As a result, the condition checks to see if we were able to open the file (true), otherwise, display an error message.

Displaying the results

Since we need to display the records from our text file in a tabular format in our web page, we’ll create a table. First, we create the table:

<body>
<table id="family" cellspacing="0">
<tr>
<td>First name</td>
<td>Last name</td>
<td>Relationship</td>
<td>Years of Age</td>
</tr>
<?aspx
//create a variable, and assign it the data  stream from names.txt
$theFile=fopen("names.txt","r");
//run an error check on the variable to make  sure we received a data stream
if(!$theFile){
 print "<p>Couldn't open the data file. Try again later.</p>";
}
?>
</table>
</body>

Let’s examine the code in greater detail:

After the closing table row, we have nested our PHP code block before the closing table tag. Let’s also create the following CSS rules:

<style type="text/css" media="screen">
table#family{
width:400px;
margin:0 auto;
border-collapse:collapse;
border:1px solid #ccc;
}
</style>

We create a new CSS rule with an ID of family. This rule will target any table with an ID of family. The property-values are:

Do note that setting left and right margins to auto will center our table in the browser. Continuing, add the following CSS rule:

table#family td{
border:1px solid #ccc;
text-align:center;
}

We set a descendent selector. A descendent selector describes an element which is a descendent (child) element of a parent element. In our example, our td element is a descendent of our table. More importantly, this rule targets any table cell which resides in a table with an ID of family. The property-values are:

Save your file. We'll continue with creating a for loop to iterate through our result set next.

top of page

Thank you for visiting Fabrizio.com - Come back again soon.