简体   繁体   中英

Removing un-wanted commas in .csv file, after pressing 'submit button'

here is the problem:

I have made a form field where people can enter their name and Adress etc.. When everything is filled and they Press send, i get the details in a .csv file. However my problem is, when a field i empty or all empty, all i get in the .csv file are ' ,,,, ' .

Here is my code:

<form method="POST" action="index.php">

    <input type="text" name="vorname"   placeholder="Vorname Eingeben">     <br>
    <input type="text" name="nachname"  placeholder="Nachname Eingeben">    <br>
    <input type="text" name="ort"       placeholder="Ort Eingeben">         <br>
    <input type="text" name="plz"       placeholder="PLZ Eingeben">         <br>
    <input type="text" name="strasse"   placeholder="Straße Eingeben">      <br>
                                                                            <br>
    <input type="submit" name='Absenden'>

</form>

PHP

$data = array (
    $_POST ['vorname'], $_POST ['nachname'], $_POST ['ort'], $_POST ['plz'], $_POST ['strasse']
);

$fp = fopen('file.csv', 'a+');
fputcsv($fp, $data);

fclose($fp);

Here is the .csv result's after the form is filled / not filled.

test1,test2,test3,test4,test5
,,,,
test3,test5,test6,test7,
test,,test,,

The; ,,,, Those are the ones that im trying to get rid of, or rather more when the form is not filled so they do not appear.

You can do the test before inserting any new line in your csv like this:

$data = array (
    $_POST ['vorname'], 
    $_POST ['nachname'], 
    $_POST ['ort'], 
    $_POST ['plz'], 
    $_POST ['strasse']
);

if(!empty(array_map('trim', array_filter($data)))) {
    $fp = fopen('file.csv', 'a+');

    fputcsv($fp, $data);

    fclose($fp);    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM