Jump to content

HTML Form data to CSV file using PHP


NickWrenLab

Recommended Posts

I need help with a php code that can take the information from a filled out html form and send the info to a csv file in the background (or on the host site). Taking a basic form as provided and the function $_POST how can I write code that will take the input data and export it to a file. If you can provide just a basic example of how a csv file is filled out or called upon using other scripts would really be appreciated.

I saw this posted however didnt really help me out, however I am looking at one of the links posted at the bottom for PHP codeacdemy help.

http://forums.phpfreaks.com/topic/298539-how-to-create-a-actionphp-page-for-html-form/

 

Also found that I could use this code to start the php, I just dont know how to apply it:

<?php header("content-type: text/csv"); ?>

HTML Form code:

<html>
<head>
</head>
<body>
<form action="basicform.php">
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname"> <br><br>
<input type="radio" name="sex" value="male" checked> Male
<br>
<input type="radio" name="sex" value="female"> Female
<br><br>
<input type="checkbox" name="box1" value="1"> #1 option
<br>
<input type="checkbox" name="box2" value="2"> #2 option
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Edited by NickWrenLab
Link to comment
Share on other sites

I added in some php code that I have been trying to get to write to a csv file.  However I still cannot get it to write to a file, I have tried the code

file_put_contents('test.csv', $fields, FILE_APPEND);

I've tried the normal fwrite and fputcsv but netiher worked

fwrite($fp, $csvData)
foreach($csvData as $fields){
	 fputcsv($fp, $fields);
 }
<!DOCTYPE html>
<html lang="en">
<head>
<?php
if (isset($_POST['Sumbit'])) {
$filename = "/test.csv";
 header('Content-Type: text/csv; charset=utf-8');
 header('Content-Disposition: attachment; filename=test.csv');
 //read data from form

 $del = "\	";
 $lastname = $_POST['lastname'];
 $firstname = $_POST['firstname'];
 $sex = $_POST['sex'];
 $box1 = $_POST['box1'];
 $box2 = $_POST['box2'];
 //generate output for text file
 $csvData = $lastname . "\t" . $firstname . "\t" . $sex . "\t" . $box1 . "\t" . $box2 . "\n" ;
 
 //open file for output
 $fp = fopen("/test.csv", "a");
 $csvData = "\\r\
 ".implode ($del, $csvData);
 //write to the file
 foreach($csvData as $fields){
	 file_put_contents('test.csv', $fields, FILE_APPEND);
 }
 fclose($fp);
}
 ?>
</head>
<body>
<form name="PatientForm" action="addContactCSV.php" method="post">
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname"> <br><br>
<input type="radio" name="sex" value="male" checked> Male
<br>
<input type="radio" name="sex" value="female"> Female
<br><br>
<input type="checkbox" name="box1" value="1"> #1 option
<br>
<input type="checkbox" name="box2" value="2"> #2 option 
<br><br>
<input type="submit" name="Submit" id="Submit" value="Submit" />
<input type="reset" name="Reset" id="button" value="Reset" />
</form> 
</body>
</html>
Edited by NickWrenLab
Link to comment
Share on other sites

If you are writing csv data then use fputcsv.

 

Minimum arguments this function takes is two.

, not a filename. You get a file resouce using fopen. You will want to set fopen's mode to a (which will write contents to and append to the end to the file)
// open the file named myfile.csv in append mode
$handler = fopen('myfile.csv'. 'a');
  • The second argument is an array of values. You will want to get the values from your form and add each value to an array

 

The other (optional) arguments allows you to specify the following (you should not need to modify these)

  • delimiter - the character which seperates each value
  • enclosure - the character which delimits the start and end of each value
  • escape character - the character to use for escaping special values in csv.
Link to comment
Share on other sites

I changed the 'fputcsv' code for the 'file_put_contents' however nothing is writing to my test.csv file.

the part I changed looks like this:

 //generate output for text file
 $csvData = $lastname . "\t" . $firstname . "\t" . $sex . "\t" . $box1 . "\t" . $box2 . "\n" ;
 
 //open file for output
 $handle = fopen('test.csv', 'a');
 $csvData = "\\r\
 ".implode ($del, $csvData);
 //write to the file
 foreach($csvData as $fields){
	 fputcsv($handle, $fields);
 }
 fclose($handler);
}
 ?>

This should do it for you http://bfy.tw/2FJa

And... Uh yea thats how I got the code that I have, aka googled it. Most of the sites I have looked up, downloaded or copied their code; tried to make changes or just took it as is and most dont work; or use and SQL database, which I am trying to prevent.

Link to comment
Share on other sites

Run this. If it doesn't work you may have a file permission issue.

$_POST['fname'] = 'Sam';
$_POST['lname'] = 'Smith';
$_POST['sex']   = 'M';

$list = array(
    array(
        $_POST['fname'],
        $_POST['lname'],
        $_POST['sex']
    )
);

$fp = fopen('test.csv', 'a');

foreach ($list as $fields)
    {
    fputcsv($fp, $fields);
    }
fclose($fp);
Link to comment
Share on other sites

I changed used the code:

<html>
<head>
</head>
<body>
<form name="form" method="post" action="<?=$_SERVER['PHP_SELF'];?>">
      Name: <input type="text" name="fname" /> <br />
      Surname: <input type="text" name="lname" /> <br />
      Home: <input type="text" name="sex" /> <br /> 
      <input type="submit" name="submit" />
    </form>
</body>
 <?php
$_POST['fname'] = 'Sam';
$_POST['lname'] = 'Smith';
$_POST['sex']   = 'M';

$list = array(
    array(
        $_POST['fname'],
        $_POST['lname'],
        $_POST['sex']
    )
);

$fp = fopen('test.csv', 'a');

foreach ($list as $fields)
    {
    fputcsv($fp, $fields);
    }
fclose($fp);
?> 
</html>

Hopefully all the code is working correctly, but as you said I might not have permission, which is something that I  didnt think would be a problem. Would you know how to give access to let the fields be populated

Link to comment
Share on other sites

<html>
<head>
</head>
<body>
<form action="basicform.php" method="post">
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname"> <br><br>
<input type="radio" name="sex" value="male" checked> Male
<br>
<input type="radio" name="sex" value="female"> Female
<br><br>
<input type="checkbox" name="box1" value="1"> #1 option
<br>
<input type="checkbox" name="box2" value="2"> #2 option
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

basicform.php

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

// set path to file
$path = __DIR__ . '\file.csv';

// open the file if it exists, if not create it
if(($fp = fopen($path, 'wb')) === false)
{
	exit('failed to open file');
}

$posts = array();

if( ! empty($_POST['firstname']))
{
	$posts['firstname'] = $_POST['firstname'];
}
if( ! empty($_POST['lastname']))
{
	$posts['lastname'] = $_POST['lastname'];
}
if( ! empty($_POST['sex']))
{
	$posts['sex'] = $_POST['sex'];	
}
if( ! empty($_POST['box1']))
{
	$posts['box1'] = $_POST['box1'];
}
if( ! empty($_POST['box2']))
{
	$posts['box2'] = $_POST['box2'];
}

// write the header row
fputcsv($fp,array_keys($posts),',');

// write a data row
fputcsv($fp, array_values($posts));

fclose($fp);

  • Like 1
Link to comment
Share on other sites

@hansford

Nice job with array_keys & array_values but its not going to work with multiple rows. When appending you are going to repeatedly insert the header row.

 

Also the b parameter is no longer an option in newer PHP. Per the Manual:

 

As of PHP 4.3.2, the default mode is set to binary for all platforms that distinguish between binary and text mode. If you are having problems with your scripts after upgrading, try using the 't' flag as a workaround until you have made your script more portable as mentioned before

Edited by benanamen
Link to comment
Share on other sites

 

 

Nice job with array_keys & array_values but its not going to work with multiple rows. When appending you are going to repeatedly insert the header row.

 

Well, the code is based on their form so no need for multiple rows. Also, If they expect multiple form submissions then they need to change the "wb" flag to "a" or "ab" or else the file is going to be overwritten each time. They will also create the file along with the headers and simply open the file and append a new data row each time.

Link to comment
Share on other sites

If you already created the file with the headers then all you need to do is append a row each time the form is submitted.

You can force users to fill in all values before writing data to the file or simply enter blank data for that column.

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

// set path to file
$path = __DIR__ . '\file.csv';

// open the file for appending
if(($fp = fopen($path, 'ab')) === false)
{
	exit('failed to open file');
}

$posts = array();

if( ! empty($_POST['firstname']))
{
	$posts['firstname'] = $_POST['firstname'];
}
else
{
        $posts['firstname']  = '';
}
if( ! empty($_POST['lastname']))
{
	$posts['lastname'] = $_POST['lastname'];
}
else
{
        $posts['lastname']  = '';
}
if( ! empty($_POST['sex']))
{
	$posts['sex'] = $_POST['sex'];	
}
else
{
        $posts['sex']  = '';
}
if( ! empty($_POST['box1']))
{
	$posts['box1'] = $_POST['box1'];
}
else
{
        $posts['box1']  = '';
}
if( ! empty($_POST['box2']))
{
	$posts['box2'] = $_POST['box2'];
}
else
{
        $posts['box2']  = '';
}

// write a data row
fputcsv($fp, array_values($posts));

// close the file
fclose($fp);
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.