views:

394

answers:

4

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);
+2  A: 

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);
Mike B
+2  A: 

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

stereofrog
Don't forget to check to make sure the cURL extension is installed.
Mike B
+1  A: 

If you already have the variable with all the data you can use file_put_contents to save it as a csv

Galen
A: 

To create the CSV you would need to break your string into an array, then loop through it. After that you can save the file to any directory the web server account has access to on your server. Here is an example ...

//variables for the CSV file $directory='\sampledir\; $file='samplefile.csv'; $filepath = $directory.$file;

//open the file $fp = fopen("$filepath",'w+');

//create the array $foo = "some value,another value,last value"; $arrFoo = explode(',',$foo);

//loop through the array and write to the file $buffer = ''; foreach($arrFoo AS $value) { $buffer .= $value."\r\n"; } fwrite($fp,$buffer);

//close the file fclose($fp);

Your file will now be written to the directory set in $directory with the filename set in $file.

-Justin

Justin Pennington