Forum Topics : Development / Creating a php.net database like with the CSV file
Hi. This code was posted by smith99 in other topic. The problem is that it's not functioning correctly, at least with the last CSV. Many records they're added without the ISO3 code, what it causes an error in the index creator. =/
Somebody could correct this code?
Grateful. ;)
if(!$csvFh = fopen("$csvFile", 'r')) {
die("Unable to open $csvFile for reading.");
}
if(!$dbFh = fopen("$dbFile.tmp", 'w')) {
die("Unable to open $dbFile.tmp for writing.");
}
$gran = 10000000;
//note: using line length of 150. More than enough, for now.
while( $fields_in = fgetcsv($csvFh, 150, ',') ) {
$fields_in[0] = str_pad($fields_in[0], 10, '0', STR_PAD_LEFT);
$fields_in[1] = str_pad($fields_in[1], 10, '0', STR_PAD_LEFT);
$from = intval($fields_in[0] / $gran);
$to = intval($fields_in[1] / $gran);
if ( $from < $to ) {
$diff = $to - $from;
$r = $fields_in[0] .
str_pad(($from * $gran + $gran - 1), 10, '0', STR_PAD_LEFT) .
$fields_in[3]. "\n";
fwrite($dbFh, $r);
for ( $i = 1; $i < $diff; $i++ ) {
$r = str_pad((($from + $i) * $gran), 10, '0', STR_PAD_LEFT) .
str_pad((($from + $i) * $gran + $gran - 1), 10, '0', STR_PAD_LEFT) .
$fields_in[3] . "\n";
fwrite($dbFh, $r);
}
$r = str_pad(($to * $gran), 10, '0', STR_PAD_LEFT) .
$fields_in[1] . $fields_in[3]. "\n";
fwrite($dbFh, $r);
} else {
$record = $fields_in[0] . $fields_in[1] . $fields_in[3] . "\n";
fwrite($dbFh, $record);
}
}
fclose($csvFh);
fclose($dbFh);