Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a CSV file using PHP (and upload it)

For example, I have a variable "$foo" that includes all the data which I want to show in the CSV:

$foo = "some value,another value,last value";

My goal is to:

  1. Create a CSV file named "some.csv" whose contents are equal to $foo

  2. Upload "some.csv" to my server.

How can this be done?

Update: Here's the exact code that worked for me.

$foo = "some value,another value,last value";
$file = 'some_data.csv';
file_put_contents($file, $foo);
like image 712
edt Avatar asked Jun 18 '26 08:06

edt


2 Answers

Number 1:

file_put_contents("foobar.csv", $yourString);

Number 2:

$c = curl_init("http://"...);  
curl_setopt($c, CURLOPT_POSTFIELDS, array('somefile' => "@foobar.csv"));
$result = curl_exec($c);
curl_close($c);
print_r($result);

note the @ before the filename

like image 58
user187291 Avatar answered Jun 20 '26 22:06

user187291


See fputcsv()

If $foo is already csv-formatted. You can use file_put_contents()

You don't specify the upload method. Here is an example using ftp (UNSECURE):

$foo = '...csv data...';
$username = "myUser";
$password = "myPassword";
$url = "myserver.com/file.csv";
$hostname= "ftp://$username:$password@$url";
file_put_contents($hostname, $foo);
like image 20
Mike B Avatar answered Jun 20 '26 21:06

Mike B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!