How to Parse a Tab-Delimited Text File Into an Array in PHP
- 1). Open a text editor and type some tab-delimited values in a new file. Enter the values by inserting a "tab" character in between each value. Save the file on the web server with the name "tabbedTextFile.txt", noting the file's location. The "(tab)" text is shown to illustrate the tabs separating each value. Save and close tabbedTextFile.txt.
value1(tab)value2(tab)value3(tab)value4(tab)value5 - 2). Return to the text editor and type a "<?php" and a "?>" PHP delimiter. These delimiters tell the server to interpret any code placed between them as PHP code. Open tabbedTextFile.txt for reading using the PHP "fopen()" function and write the returned value to a variable named "$openFile". Save the file as "parseToArray.php".
<?php
$openFile = fopen("tabbedTextFile.txt", "r");
?> - 3). Continue editing parseToArray.php. Use the PHP "fread()" function to read the contents of tabbedTextFile.txt to a variable named "$fileContents". Use the PHP "filesize()" function to indicate that the entire file should be read.
<?php
$openFile = fopen("tabbedTextFile.txt", "r");
$fileContents = fread($openFile, filesize("tabbedTextFile.txt"));
?> - 4). Continue editing parseToArray.php and enter the PHP "fclose()" function. This function closes tabbedTextFile.txt.
<?php
$openFile = fopen("tabbedTextFile.txt", "r");
$fileContents = fread($openFile, filesize("tabbedTextFile.txt"));
fclose($openFile);
?> - 5). Continue editing parseToArray.php. Identify the delimiter (tab) that should be used when parsing tabbedTextFile.txt. Store the delimiter to a variable named "$delimiter".
<?php
$openFile = fopen("tabbedTextFile.txt", "r");
$fileContents = fread($openFile, filesize("tabbedTextFile.txt"));
fclose($openFile);
$delimiter = "";
?> - 6). Continue editing parseToArray.php. Use the PHP "explode()" function to extract the values in tabbedTextFile.txt, specifying that delimiter stored in $fileContents (tab). Write the exploded values to a variable named "$myArray". The "explode()" function returns an array of values.
<?php
$openFile = fopen("tabbedTextFile.txt", "r");
$fileContents = fread($openFile, filesize("tabbedTextFile.txt"));
fclose($openFile);
$delimiter = "";
$myArray = explode($delimiter, $fileContents);
?> - 7). Continue editing parseToArray.php. Print the values of $myArray array using the "print_r" command. The "print_r" command prints readable information about a variable. Save and close parseToArray.php.
<?php
$openFile = fopen("tabbedTextFile.txt", "r");
$fileContents = fread($openFile, filesize("tabbedTextFile.txt"));
fclose($openFile);
$delimiter = "";
$myArray = explode($delimiter, $fileContents);
print_r($myArray);
?> - 8). Open a web browser and access parseToArray.php on the web server. Verify that the array values are printed on the web page.