PHP - English

Text Files and Arrays in PHP



There is another option you can use to place lines of text into an array. In
the technique below, we’re using the explode( ) string
function to create an array from each line of text. Here’s the code (this assumes
that you’ve been following along from the previous sections):


$file_handle = fopen(“dictionary.txt”, “rb”);

while (!feof($file_handle) ) {

$line_of_text = fgets($file_handle);
$parts = explode(‘=’, $line_of_text);

print $parts[0] . $parts[1]. “<BR>”;




The lines to examine are in blue; the rest you have met before (get a file
handle, loop round, use fgets to read the line). The first line to note
is this:

$parts = explode( ‘=’, $line_of_text );

If you remember the string section, you’ll also be familiar with the explode
function. It splits a line of text, based on whatever you have provided for
the separator. In our code, we have used the equals sign ( = ) as a separator.
This is because each line in the dictionary.txt file looks like this:

AAS = Alive and smiling

When the explode function is executed, the variable called $parts will
be an array. In our text file there will only be two positions in the array,
one for each half of the equals sign.

We then print out both parts of the array with this:

print $parts[0] . $parts[1]. “<BR>”;

So $parts[0] will hold the abbreviation (AAS) and $parts[1] will
hold the meaning.

The next time round the while loop, the second line will be read from the text
file. Exactly the same thing happens, so the line will be split again, and placed
into an array. This is a good technique to use, if you want to split each line
and do something different with each part of the line.


In the next part, we’ll take a look at File Locations, and how to work with


Kaynak : ‘sitesinden alıntı

Yorum Yap