2

I have a problem. I’ve created a web form in HTML that stores data from inputs in CSV file through PHP file using fputcvs function. Now... When I open that CSV file in Excel, or via =IMPORTDATA function in google sheets, it deletes leading zeros (0). The leading zeros are very important in my case. Any way or trick to fix it through the PHP or HTML file? Thanks

My PHP code:

<?php

$fieldA = $_POST["prezime"];
$fieldB = $_POST["ime"];
$fieldC = $_POST["datumrodjenja"];
$fieldD = $_POST["mestorodjenja"];
$fieldE = $_POST["rod"];
$fieldF = $_POST["prebivaliste"];
$fieldG = $_POST["brojpasosa"];
$fieldH = $_POST["izdatod"];
$fieldI = $_POST["vazido"];
$fieldJ = $_POST["profesija"];
$fieldK = $_POST["zanimanje"];
$fieldL = $_POST["fiksni"];
$fieldM = $_POST["mobilni"];
$fieldN = $_POST["email"];
$fieldO = $_POST["napomena"];

$keys = array($fieldA,$fieldB,$fieldC,$fieldD,$fieldE,$fieldF,$fieldG,$fieldH,$fieldI,$fieldJ,$fieldK,$fieldL,$fieldM,$fieldN,$fieldO); //THIS IS WHERE YOU PUT THE FORM ELEMENTS ex: array('$fieldA','$fieldB',etc)

$keys = ["prezime", "ime", "datumrodjenja", "mestorodjenja", "rod", "prebivaliste",
     "brojpasosa", "izdatod", "vazido", "profesija", "zanimanje", "fiksni", "mobilni",
     "email", "napomena"];

$labels = ["Prezime", "Ime", "Datum Rođenja", "Mesto Rođenja", "Rod", "Prebivalište",
     "Broj Pasoša", "Izdat Od", "Važi Do", "Profesija", "Trenutno Zanimanje", "Tel. Fiksni", "Tel. Mobilni",
     "E-mail Adresa", "Napomena"];

$values = [];
foreach ($keys as $key)
    $values[] = $_POST[$key];

$fname = 'prijave.csv';
if (!file_exists($fname)) {
    $fp = fopen($fname,'a');
    //add BOM to fix UTF-8 in Excel
    fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
    fputcsv($fp, $labels);
}
else {
    $fp = fopen($fname,'a');
}
fputcsv($fp, $values);
fclose($fp);
kuzmvnovic
  • 35
  • 1
  • 8
  • 1
    Hope this will be helpful:- [How to keep leading zeros in PHP integer](https://stackoverflow.com/questions/18148486/how-to-keep-leading-zeros-in-php-integer) – Alive to die - Anant Apr 16 '18 at 05:39
  • This is more about how applications read CSV files. If you need it to be a spreadsheet, it's best to create the spreadsheet rather than a CSV. IF you want a really nasty way of forcing it - change the field value to `="0000001"` – Nigel Ren Apr 16 '18 at 06:35
  • Can you provide sample data in $_POST so we can recreate your code properly? `$_POST=["prezime"=>"94820", "ime"=>"0124757",...]` – miken32 Apr 16 '18 at 16:18
  • In excel file you can not print leading zeros but you can see them on notepad. – ashish bansal Apr 16 '18 at 05:42

0 Answers0