Parse A Tab-delimited .TXT File Into An Array With File(); Function?May 29, 2009
I have a tab-delimited .TXT file that I'm trying to process and insert into a MySQL database. The file() function will write each row of the text file as a separate element in an array. So, my text file (see attached) is pretty simple and only has 2 rows... the first row contains the column headers, i.e. "Column A, Column B, Column C..." and the second row contains the values. i.e. "Value A, Value B, Value C..."
However, I'm running into a problem because several of the columns actually contain multiple values separated by carriage returns (line breaks), and the file() function doesn't seem to like this:
| Column C |
| > Value C1 |
| > Value C2 |
| > Value C3 |
Here's my code:
// Read each row into an array as separate elements
$Rows_array = file(MyText.txt);
// Output the column headers
So, it seems like the file() function does what it's supposed to until it gets to the first line break. Also, a doublequote (") appears before the first value in the column with the carriage return, so I'm sure there's some sort of escaping issue.
Note: I tried file_get_contents() as well to try and get the row into a string instead of an array, and it gives the same result. Ultimately, I AM just going to throw out the line breaks and explode() the values in Column C as their own array or string, but I need to get all those values passed to my PHP code first, which is where I'm struggling. And, I really want to avoid "pre-processing" the txt file by opening it in excel or something and removing the carriage returns in the culprit columns.