0

I want to store my PHP variable in a CSV file.

As they are individual variables and I need to store them in row columns format.

for ex- ID, First Name, Last Name, Address, Phone. etc.

suppose I have variable $id, $firstname, $lastname, $address, $phone.

How can I store this variable in a single row separated by a column in a CSV file?

I tried using an array but as they are individual variables and use in entire my program so I want to add this variable at end of the script to CSV to maintain the report.

$fp = fopen($filename, "w");

$fp = fopen("ouput.csv", w)

fputcsv($fp,array(array($id,$firstname, $lastname,$address,$phone)));

fclose($fp);

Thanks in advance.

3
  • Show us what you tried. This isn't a coding service where we write all the code for you. Commented Jan 25, 2016 at 7:08
  • Did you want to store variable value or variable name to csv file? Commented Jan 25, 2016 at 7:08
  • I want to store variable value in csv, As first I am importing data from csv and storing into database. Then I want to store that variable which are inserted or updated using previous queries into csv file. Commented Jan 25, 2016 at 7:12

4 Answers 4

1

You were very close, instead of:

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

you should have called:

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

The w causes the file to overwrite, the a stands for append.

Sign up to request clarification or add additional context in comments.

Comments

0

Just try this :

$string = $id . "," . $firstname . "," . $lastname . "," . $address . "," . $phone;

file_put_contents("ouput.csv", $string."\n", FILE_APPEND);

2 Comments

Also not necessarily correct. this will 100% fail if your address contains a comma or newline for example. Pretty bad idea
This is a really bad answer.
0

Check fputcsv function in the manual.

From the example in the manual:

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

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

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

fclose($fp);
?>

Comments

0

I got best Solution to separately save data column wise. fputcsv is able to handle large no of records very efficiently. also if the content with escape characters like , "" '' it will still add data properly in csv file ..

fputcsv($csvfileoutput, array($id,$firstname,,$lastname, $address,$mobilenumber));	
				

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.