fgets / fwrite loop php -


am having problem loop.

i have text file looks this

an xixerella

an vila

an sornas

an soldeu

an sispony

an segudet

an el tarter

an sant julia de loria

an sant joan de caselles

to exception have more 2 million lines.

i need sql request insert

for last 12 hours i've been trying no success

i've tried this

<?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 $k => $v){      echo $ex[0].' '. $ex[1];     echo '<br>';      $fw = fwrite($nf, "('" . $ex[0] . "','"  . $ex[1] . "')\r\n");  } }       fclose($f); fclose($nf); ?> 

or

$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 $k => $v){      // echo $ex[0].' '. $ex[1];     // echo '<br>';      $fw = fwrite($nf, "('" . $ex[0] . "','"  . $ex[1] . "')\r\n");    } }      fclose($f); fclose($nf); 

but both times had in written file

('an','xixerella')

('an','xixerella')

('an','xixerella')

('an','vila')

('an','vila')

('an','vila')

each line being repeated 3 times , cant figure out why.

thanks in advance help

because have foreach loop nested in while loop, you're breaking lines many pieces needlessly, , logic flawed.

<?php $infile = "cities.txt"; $outfile = "cities.sql"; $rh = fopen($infile, "r"); $wh = fopen($outfile, "w+");  //this has change because blank line or line '0' break loop while( ($line = fgets($rh, 4096000)) !== false ) {     $parts = preg_split('/\s+/', $line, 2); //limit splitting 2 parts, state , 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); 

Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -