Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有办法将文件的每一行分割成数组的一个元素| PHP_Php_Arrays_File_Line_Explode - Fatal编程技术网

有没有办法将文件的每一行分割成数组的一个元素| PHP

有没有办法将文件的每一行分割成数组的一个元素| PHP,php,arrays,file,line,explode,Php,Arrays,File,Line,Explode,直截了当地说:不,这不是“通常的问题”,是的-我读过其他关于这个主题的StackOverflow文章,它们没有帮助我 如果在文件中创建数组并查看输出: $names = ["test123", "test!?", "test"]; var_dump($names); 输出: array(3) { [0]=> string(7) "test123" [1]=> string(6) "test!?" [2]=> string(4) "test" } ar

直截了当地说:不,这不是“通常的问题”,是的-我读过其他关于这个主题的StackOverflow文章,它们没有帮助我

如果在文件中创建数组并查看输出:

$names = ["test123", "test!?", "test"];
var_dump($names);
输出:

array(3) {
  [0]=>
  string(7) "test123"
  [1]=>
  string(6) "test!?"
  [2]=>
  string(4) "test"
}
array(3) {
  [0]=>
" string(8) "test123
  [1]=>
" string(7) "test!?
  [2]=>
  string(4) "test"
}
。。。这是完全正确的。3个元素,每个元素组成一个字符串

但如果您通过explode读取文件的行并将其输入到数组中:

$names = explode("\n", file_get_contents('list.txt'));
var_dump($names);
输出:

array(3) {
  [0]=>
  string(7) "test123"
  [1]=>
  string(6) "test!?"
  [2]=>
  string(4) "test"
}
array(3) {
  [0]=>
" string(8) "test123
  [1]=>
" string(7) "test!?
  [2]=>
  string(4) "test"
}
。。。这与第一个不同,因为这些都是字符串,但(不包括最后一个)每个字符串多一个字符+不作为上面的数组引用


那么我的问题是:我如何将文件的所有行读入数组的元素中,并使用我提供的第一个示例的准确拼写?我需要一个“普通数组”的确切格式,以便进一步的程序使用,但我无法使它工作:)

我想您可以使用这行代码

$lines = file($filename, FILE_IGNORE_NEW_LINES);

我想你可以用这行代码

$lines = file($filename, FILE_IGNORE_NEW_LINES);

你在Windows机器上工作吗?然后换行符被标记为\r\n,最安全的方法是通过告诉他们您在Windows机器上工作吗?然后换行符用\r\n标记,最安全的方法是使用heithem moumni的答案