简体   繁体   中英

php save to csv file

I'm wanting to store basic data from a single form box and I've created this php code base, but it doesn't seem to be working. Can someone take a glance and see if anything stands out to why this wouldn't work. Edit: the csv file never updates with new data

if (isset($_POST["submit"])) 
{ 
    $name = $_POST["name"]; 
    date_default_timezone_set('America/New_York');
    $date = date('Y-m-d H:i:s');

    if (empty($name)) 
    { 
        echo "ERROR MESSAGE"; 
        die; 
    } 
    $cvsData ='"$name","$date"'.PHP_EOL; 
    $cvsData .= "\"$name\",\"$date\"".PHP_EOL; 
    $fp = fopen("emailAddressses.csv", "a");

    if ($fp) 
    { 
        fwrite($fp,$cvsData); // Write information to the file 
        fclose($fp); // Close the file 
    }
}

Use the nicer way in php : fputcsv

Otherwise you need to do lot of error handling to achieve in your case.

$list = array (
    array('First Name', 'Last Name', 'Age'),
    array('Angelina ', 'Jolie', '37'),
    array('Tom', 'Cruise', '50')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

You should look into fputcsv . This will add CSV to you file and take care of fields and line ends.

fputcsv($fp,array(array($name,$date)));

You can also specify delimiters and such if you want.

This part will not behave like you expect, the variables are not evaluated when inside single quotes:

$cvsData ='"$name","$date"'.PHP_EOL;

You will need to use double quotes:

$cvsData ="\"$name\",\"$date\"".PHP_EOL; 

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