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
480

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 usefile() instead.

$members = array_map('trim', file($fileName, FILE_IGNORE_NEW_LINES));

With the example file you showed, this should result in

$members = ['13456', '23789', '14789', '09678', '45678'];
542

Answer

Solution:

You can simply put the lines into an array and use print_r instead of echo to print that array

while ($line = fgets($file)) {
  $members[] = $line;
}
print_r($members);
59

Answer

Solution:

It should depend on the file that you are dealing with.

FileType:

  • text -> fgets($file)
  • CSV -> fgetcsv($file)

People are also looking for solutions to the problem: PHP IF statement testing decoded JSON data

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.