html - Php - Reading file lines into an array
572
The numbers in my file are 5X5:
13456
23789
14789
09678
45678
I'm trying to put it into this form
array[0]{13456}
array[1]{23789}
array[2]{14789}
array[3]{09678}
array[4]{45678}
My code is:
$fileName = $_FILES['file']['tmp_name'];
//Throw an error message if the file could not be open
$file = fopen($fileName,"r") or exit("Unable to open file!");
while ($line = fgets($file)) {
$digits .= trim($line);
$members = explode("\n", str_replace(array("\r\n","\n\r","\r"),"\n",$digits));
echo $members;
The output I'm getting is this:
ArrayArrayArrayArrayArray
Answer
Solution:
fgets
gets a line from the file pointer, so theoretically there should be no"\r"
or"\n"
characters in$line
.explode
will still work, even if the delimiter is not found. You'll just end up with an array with one item, the entire string. You can't echo an array, though. (That's why you're seeingArray
for each line; it's the best PHP can do when you useecho
on an array.)If I were you, I would rather just use
file()
instead.With the example file you showed, this should result in
Answer
Solution:
You can simply put the lines into an array and use print_r instead of echo to print that array
Answer
Solution:
It should depend on the file that you are dealing with.
FileType: