逐行读取文件并提取值

时间:2014-10-24 11:05:31

标签: php

我需要做一个能够从文件中提取值并将这些值发送到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 ) 

似乎对于每个其他cicle,fgets()函数返回一个&#34; \ n \ r&#34;而且我不知道如何摆脱它。

编辑:

我已经使用了trim()str_replace()并得到了相同的结果,所以也许我没有得到&#34; \ n \ r&#34;。

2 个答案:

答案 0 :(得分:0)

摆脱\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>

答案 1 :(得分:0)

<?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;
相关问题