Output Data from Text File with PHP

Written by admin on May 7th, 2008 in PHP Tutorials, General.

In this tutorial I am going to teach you how to generate data from a text file with the use of PHP.

To start you must first make a document called data.txt

Open up your data.txt for editing (I highly recommend using Notepad++).

Now put the following code into your text file.


| News 1 | News 2 | News 3

The above is what we can output. Each phrase is separated by a |. We need this so that we can tell our php script when to stop outputting a piece of data.

Now you need to make a PHP file called quotes.php.

This is the file that will generate our data.
Insert the following code into your php file.



<?php

$data = file(’data.txt);
$data = array_reverse($data);
foreach($data as $key=>$element) {
$element = trim($element);
$pieces = explode(”|”, $element);
echo $pieces[2] . “<br /><br />
\n”;
}
?>

The above code may seem complex but lets run through it.

To start with we have made a variable called $data. In the variable we have got a file called quotes.txt and have now got all the data in an array.

Then we added to our data variable to reverse all of the data. (This will make it more random).

Then we have used a function called foreach. This simply outputs anything in its brackets however many times there is a value with the value outputted.
Then we are saying for ever $data (our array) is $key=>$element.

This is getting our data from our text file so we can use it.

Next we are using trim. This trims our text down using the trim(); function.

This is the most vital bit of the script.


$pieces = explode("|", $element);

We have made a new variable called $pieces. In this we are creating an array. We are making a new array value every time our script reads a |. So every time a | is read it will stop and make a new value.

Explode makes an array with the value before what it exploded. So anything before the | will be a value. So we need to get the next value. so we say $pieces[1] to get our data.

That will output each piece of data separately.

Enjoy!

Leave a Reply

You must be logged in to post a comment.



Site Navigation