Php - 将文件行读入数组

标签 php html algorithm file

我文件中的数字是 5X5:

13456
23789
14789
09678
45678

我正在尝试将其放入此表单中

array[0]{13456}
array[1]{23789}
array[2]{14789}
array[3]{09678}
array[4]{45678}

我的代码是:

$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;

我得到的输出是这样的:

ArrayArrayArrayArrayArray

最佳答案

fgets 从文件指针中获取一行,所以理论上应该没有 "\r""\n" 字符$行explode 仍然有效,即使没有找到分隔符。您最终会得到一个包含一个项目的数组,即整个字符串。但是,您不能回显数组。 (这就是为什么您在每一行中看到 Array 的原因;当您在数组上使用 echo 时,这是 PHP 可以做的最好的事情。)

如果我是你,我宁愿只使用 file()

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

使用您显示的示例文件,这应该导致

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

关于Php - 将文件行读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070918/

相关文章:

php - 如何在所有页面上使用 css 将 element.style 更改为无

html - col-xl-* 的静态宽度(Bootstrap 4)?

algorithm - 编程: Give the count of all such numbers which have 3 in their decimal representation

HTML 禁用按钮获取 :active CSS Pseudo Class

algorithm - 使用动态规划最大化

algorithm - 您如何比较两个列表的顺序相同的程度?

php - Laravel 和 Mailgun 无法正常工作

php - FFMPEG视频转换时间过长

javascript - 将 div id 传递到 PHP 变量

html - 元素被其他元素压低