A B C D E F G H IAs you can see there are two types of delimitations here. There are the lines, that are being delimited by a new line character ("rn" in Windows, "n" in Unix), and then in each line, the values are being delimited by a tab ("t"). In our code we're first going to delimit the file into lines, and while we loop through those lines we split each value apart using the explode() function. This will create a second dimesion to the array where the values are being stored.
Let's start with the first part, preparing the variables:
// This is what the sample file contains:
// A B C
// D E F
// G H I
// File location (URL or server path)
$FilePath = "SampleFile.txt";
// Stores the content of the file
$Lines = file($FilePath);
// Counts the number of lines
$LineCount = count($Lines);
// This will be a two dimensional array that holds the content nicely organized
$Data = array();
// We will use this as an index
$i = 0;
The file path that's being specified can be an absolute path, relative path or URL. The line count is important so that we loop through all the lines in the file. Following that an array is created, that will be our most important object in this piece of code.
Now comes the loop that does it all:
// Loop through each line
foreach($Lines as $Value)
{
// In the array store this line with values delimited by t (tab) as separate array values
$Data[$i] = explode("t", $Value);
// Increase the line index
$i++;
}
The final lines of code will just extract three sample values from our newly created array for demonstration purposes:
// Will return A
echo "First row, first column: ".$Data[0][0]."<br />";
// Will return E
echo "Second row, second column: ".$Data[1][1]."<br />";
// Will return G
echo "Third row, first column: ".$Data[2][0]."<br />";
The beauty of this code is its simplicity and the minimum need of modification in order to adapt it to your own needs. It has no set limits for the number of rows or columns that the array can hold, and no need to specify the size of the array.
discuss this topic to forum
