如何使用php从空格分隔的.txt文件中读取数据

时间:2014-01-11 02:19:50

标签: php

我有以下代码仅用于测试目的

$file = "test.txt";

$resource = fopen($file,"w");

$content = file($file);

fclose($resource);

$ file 中的内容如下

1 5 2 6 142423 2 435 231 5 252 3224 325 54 232

我看过file()通过换行符返回数组中的内容。我真正想要的是将其推入阵列,但我不知道如何在 PHP 中建立模式。对此有何帮助?非常感谢你!

3 个答案:

答案 0 :(得分:3)

使用explode

$file = "test.txt";
$content = file_get_contents($file);
$arr = explode(" ", $content);
print_r($arr);

输出将是:

Array
(
    [0] => 1
    [1] => 5
    [2] => 2
    [3] => 6
    [4] => 142423
    [5] => 2
    [6] => 435
    [7] => 231
    [8] => 5
    [9] => 252
    [10] => 3224
    [11] => 325
    [12] => 54
    [13] => 232
)

答案 1 :(得分:3)

我认为你把事情搞混了,如果你想把它作为一个数组,函数file

 $file = "./test.txt";
 $content = file_get_contents($file, FILE_USE_INCLUDE_PATH);
 $array_contents = explode(" ", $content);

答案 2 :(得分:0)

$file_content = file("text.txt");

foreach($file_content as &$line){
    $line = explode(" ", $line);
}