Viewed   107 times

I am a novice programmer and I searched a lot about my question but couldn't find a helpful solution or tutorial about this.

My goal is I have a PHP array and the array elements are showing in a list on the page.

I want to add an option, so that if a user wants, he/she can create a CSV file with array elements and download it.

I don't know how to do this. I have searched a lot too. But yet to find any helpful resource.

Please provide me some tutorial or solution or advice to implement it by myself. As I'm a novice please provide easy to implement solutions.

My array looks like:

Array
(
    [0] => Array
        (
            [fs_id] => 4c524d8abfc6ef3b201f489c
            [name] => restaurant
            [lat] => 40.702692
            [lng] => -74.012869
            [address] => new york
            [postalCode] => 
            [city] => NEW YORK
            [state] => ny
            [business_type] => BBQ Joint
            [url] => 
        )

)

 Answers

4

You can use the built in fputcsv() for your arrays to generate correct csv lines from your array, so you will have to loop over and collect the lines, like this:

$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
    fputcsv($f, $line);
}

To make the browsers offer the "Save as" dialog, you will have to send HTTP headers like this (see more about this header in the rfc):

header('Content-Disposition: attachment; filename="filename.csv";');

Putting it all together:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://memory', 'w'); 
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // reset the file pointer to the start of the file
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}

And you can use it like this:

array_to_csv_download(array(
  array(1,2,3,4), // this array is going to be the first row
  array(1,2,3,4)), // this array is going to be the second row
  "numbers.csv"
);

Update:
Instead of the php://memory you can also use the php://output for the file descriptor and do away with the seeking and such:

function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'";');

    // open the "output" stream
    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
    $f = fopen('php://output', 'w');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
}   
Thursday, September 8, 2022
4

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

Monday, August 29, 2022
2

Try:

date('Y-m-d H:i:s', strtotime($date));

Instead of:

$date = new DateTime($date);

>

Be sure to try an if else structure:

if(strlen($date) == 10){
        $date = explode('-',$date);
        $M= $date[0];
        $D = $date[1];
        $Y = $date[2];
       //this $date = $Y.'-'.$m.'-'.$d;
       //or this =>
       $date = date('Y-m-d H:i:s', mktime($h, $m, $s, $M, $D, $Y));
    }else{
         $date = date('Y-m-d H:i:s', strtotime($date));
    }

    return $date;
Wednesday, October 19, 2022
 
5

Don't write csv file's manually. Use the built in function.

e.g. http://uk3.php.net/manual/en/function.fputcsv.php

<?php

$delimiter = ',';
$enclosure = '"';

$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, $delimiter, $enclosure);
}

fclose($fp);
?>

The above code will create a file called file.csv with your data on it. If you then want to send this file to the user as a CSV file, you can do this:

<?php

// Send the generated csv file to the browser as a download
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('file.csv');

?>

Alternatively, you can send the CSV file to download directly without creating the file on server like this:

<?php

// mini-config
$delimiter = ',';

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

// Send headers
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

// Output csv data
foreach ($list as $row) {
    echo implode($delimiter, $row) . "rn";
}

?>

Hope this helps.

Friday, October 14, 2022
2

I thought creating a new dataframe for this was a bit misguided, so I cobbled together a cat-based solution: (it could be easily modified to write to a file.)

cat( cat('BusinessId,Campaignname','n'), 
    apply( Data.csv, 1, function( ln){
       cat( ln[1], ',', paste('geo', ln[2],ln[3], sep="|"), "n")
       cat( ln[1], ',', paste("cat", ln[4],ln[5], sep="|"), "n") }))

BusinessId,Campaignname 
12 , geo|California|Los Angeles 
12 , cat|Ray brothers|IT 
34 , geo|texas|Dallas 
34 , cat|abc|TV 
45 , geo|washington|seattle 
45 , cat|Microsft|Software 
Friday, September 2, 2022
 
wod
 
wod
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :