user3408779 user3408779 - 3 months ago 25
MySQL Question

import csv file into mysql using phpexcel but leading zeros are removing

Data in my csv file looks like this.When i try to use below code the leading zeros are removing

000086;Grand Trunk Schlafsack, grün;892902000086;1;34,27
000109;Grand Trunk Hängematte, grün;0892902000109;1;15,57
000116;Grand Trunk Hängematte, blau;0892902000116;1;15,57


below is my code to import csv into myssql using phpexcel

$objReader = PHPExcel_IOFactory::createReader('CSV');
try {
$inputFileType = 'CSV';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader = $objReader->setDelimiter(";");
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$NewArray = $objPHPExcel->getActiveSheet()->toArray();
echo '<pre>';
print_r($NewArray);


My out put from the above code is

[0] => Array
(
[0] => 86
[1] =>
[2] => 892902000086
[3] => 1
[4] => 34,27
)
[1] => Array
(
[0] => 109
[1] =>
[2] => 892902000109
[3] => 1
[4] => 15,57
)
[2] => Array
(
[0] => 116
[1] =>
[2] => 892902000116
[3] => 1
[4] => 15,57
)
Here in array[0] leading zeros are removed .But I need same values as in csv like
000086
000109
000116
How can i achieve this? Any help would be greatly appreciated.

Answer

I guess that it is automatically converting it to a number, try to run a simple loop to convert it back to a string

foreach ($NewArray as &$row) {
    $row[0]= sprintf("%06d", $row[0]);
}