We are trying to import a CSV file via PHP into MySQL. The character encoding is utf-8 (checked, normalised and verified). When importing using a MySQL client interface tool all of the rows are present. The code is as follows:
$handle = fopen($this->file_name, 'r+') or die ('cant open a '.$this->file_name);
$new_filename = $upload_directory.'/'.date('Y_m_d_H_i_s').'_data_import.csv';
$for_import = fopen($new_filename, 'x+') or die ('cant open a '.$new_filename.'_for_import');
$data = array();
$row_counter = 0;
while (($row = fgetss($handle)) !== false)
{
$row = fgetss($handle);
if (($row_counter > $this->rows_to_ignore))
{
$enc = mb_detect_encoding($row);
$row = iconv($enc, 'UTF-8', $row);
$row = str_replace(", ", '\\, ', $row);
$row = trim($row);
$row = str_getcsv($row, ',', '"', '\\');
fputcsv($for_import, $row, ',', '"');
}
$row_counter++;
}
fclose($for_import);
fclose($handle);
The row_counter variable returns approx 50% of all rows. Any ideas?
Thanks
You’re calling
$row = fgetts($handle)twice. The first call is in yourwhile()condition and consumes a row, the second is inside the loop and consumes another row. The rows from the first call are being lost.