fgets / fwrite循环php

时间:2013-07-31 23:59:43

标签: php loops fwrite fgets

我遇到循环问题。

我有一个看起来像这样的文本文件

AN Xixerella

AN Vila

AN Sornas

AN Soldeu

AN Sispony

AN Segudet

AN El Tarter

Sant Julia de Loria

AN Sant Joan de Caselles

除了我有超过200万行。

我需要将其转换为插入的SQL请求

过去12小时我一直在尝试没有成功

我试过这样的

<?php
$file = "cities.txt";
$file_w = "cities.sql";
$f = fopen($file, "r");
$nf = fopen($file_w, "w+");

for($l = 0; $l<2; $l++){


$line = fgets($f);
$ex = preg_split('/\s+/', $line);

foreach($ex as $k => $v){

    echo $ex[0].' '. $ex[1];
    echo '<br>';

    $fw = fwrite($nf, "('" . $ex[0] . "','"  . $ex[1] . "')\r\n");

}
}






fclose($f);
fclose($nf);
?>

甚至喜欢这个

$file = "cities.txt";
$file_w = "cities.sql";
$f = fopen($file, "r");
$nf = fopen($file_w, "w+");

while ($line = fgets($f, 4096000))  {
    // echo $line;


$ex = preg_split('/\s+/', $line);
// var_dump($ex);die();
foreach($ex as $k => $v){

    // echo $ex[0].' '. $ex[1];
    // echo '<br>';

    $fw = fwrite($nf, "('" . $ex[0] . "','"  . $ex[1] . "')\r\n");



}
}





fclose($f);
fclose($nf);

但两次我在我的书面文件中都有这个

( 'AN', 'Xixerella')

( 'AN', 'Xixerella')

( 'AN', 'Xixerella')

( 'AN', '维拉')

( 'AN', '维拉')

( 'AN', '维拉')

每一行重复3次,我无法弄清楚原因。

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

因为你的while循环中嵌套了foreach循环,所以你不必要地将你的行分成了太多的部分,并且你的逻辑是有缺陷的。

<?php
$infile = "cities.txt";
$outfile = "cities.sql";
$rh = fopen($infile, "r");
$wh = fopen($outfile, "w+");

//this has to change because a blank line or a line that is simply '0' will break the loop
while( ($line = fgets($rh, 4096000)) !== false ) {
    $parts = preg_split('/\s+/', $line, 2); //limit to splitting into TWO parts, state and city.
    $state = $parts[0];
    $city = preg_replace("/'/", '&#39;', $parts[1]); //replace stray apostrophes
    $output = sprintf("('%s','%s')\r\n", $state, $city)
    fwrite($wh, $output)
}

fclose($rh);
fclose($wh);