逐行读取文件并提取值


Reading a file line by line and extract values

我需要执行一个例程,该例程能够从文件中提取值,并将这些值发送到mySQL数据库。

然而,我的常规是返回一些,imo,奇怪的结果。

这是我的代码:

$file = new SplFileObject($file_name);
for($i = 1 ; $i <= 5 ; $i++)
//while (!$file->eof())
{
    $linha = $file->fgets();
    echo $linha.'<br>';
    $line = explode(" ", $linha);
    print_r($line);
    echo '<br'>;
}
$file = null;

我曾经有一个while循环来运行整个文件,但遇到了一个错误,然后决定做一个for循环来获得较少的结果。

我得到的结果是:

1 1412114400 100 20 10 2 1 80 15 8 1.5 true 20 5 
Array ( [0] => 1 [1] => 1412114400 [2] => 100 [3] => 20 [4] => 10 [5] => 2 [6] => 1 [7] => 80 [8] => 15 [9] => 8 [10] => 1.5 [11] => true [12] => 20 [13] => 5 ) 
Array ( [0] => ) 
2 1412114460 100 20 10 2 1 80 15 8 1.5 true 20 5 
Array ( [0] => 2 [1] => 1412114460 [2] => 100 [3] => 20 [4] => 10 [5] => 2 [6] => 1 [7] => 80 [8] => 15 [9] => 8 [10] => 1.5 [11] => true [12] => 20 [13] => 5 ) 
Array ( [0] => ) 
3 1412114520 100 20 10 2 1 80 15 8 1.5 true 20 5 
Array ( [0] => 3 [1] => 1412114520 [2] => 100 [3] => 20 [4] => 10 [5] => 2 [6] => 1 [7] => 80 [8] => 15 [9] => 8 [10] => 1.5 [11] => true [12] => 20 [13] => 5 ) 

似乎每隔一个循环,fgets()函数都会返回一个"''n''r",我不知道如何消除它。

编辑:

我使用了trim()str_replace(),得到了相同的结果,所以可能我没有得到"''n''r"。

<?php
$file = new SplFileObject($file_name);
$i = 1;
while ($i <= 5) {  
    $linha = trim($file->fgets());
    if ($linha == '') {
        continue;
    }
    echo $linha.'<br>';
    $line = explode(" ", $linha);
    print_r($line);
    echo '<br>';
    $i++;
}
$file = null;

要摆脱'r'n使用:

$line = str_replace(array("'r", "'n", "'r'n"), array('', '', ''), $line);

我还建议使用file_get_contents(),因为它提供了一种更干净的读取文件的方式:http://php.net/manual/en/function.file-get-contents.php

您的第二个<br> 中也缺少一个>