0
votes

I want to read an excel file with Phpexcel and insert data into database, i can read everything and it's work fine but i can't read phone number with leading zero by Phpexcel when i see my database all the phone numbers saved without the leading zero like this:0212365498 saved as 212365498

1
Have you tried reading them as strings instead of integers? - Peon
I think you cannot store number begin with zero in DB (assuming your DB field is INT) . Try changing the type of field from INT to VARCHAR. This may help : stackoverflow.com/questions/2786193/… - Makesh
i have tried to reading as string but it's not work - Mo Saeedi
As I mentioned problem is at your DB side - Makesh
thanks Makesh it's work for me - Mo Saeedi

1 Answers

4
votes

If you are importing from a CSV file you can use a value binder to retain any leading zero. This is how I implemented my fix.

Created a class called 'BindValueAsString'

class BindValueAsString extends PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder
{
    public function bindValue(PHPExcel_Cell $cell, $value = null)
    {
        $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING);
        return true;
    }
} 

Set value binder before loading the CSV file

$objReader    = PHPExcel_IOFactory::createReader('CSV');
PHPExcel_Cell::setValueBinder(new BindValueAsString());
$objPHPExcel  = $objReader->load('file.csv');
$worksheet    = $objPHPExcel->getActiveSheet();
$dataAsString = $worksheet->toArray();

And that's it. Or you can just upgrade to version 1.8.1 where leading zeros are fixed here