fgets/fwrite循环php
我的循环有问题 我有一个文本文件,看起来像这样fgets/fwrite循环php,php,loops,fwrite,fgets,Php,Loops,Fwrite,Fgets,我的循环有问题 我有一个文本文件,看起来像这样 <?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){
<?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);
?>
安克瑟雷拉
维拉
索纳斯
索尔德
小马
独奏曲
艾尔塔特酒店
圣朱莉娅·德洛里亚酒店
圣女贞德卡塞勒斯酒店
除了我有超过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);
?>
因为您在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("/'/", ''', $parts[1]); //replace stray apostrophes
$output = sprintf("('%s','%s')\r\n", $state, $city)
fwrite($wh, $output)
}
fclose($rh);
fclose($wh);