Asked  8 Months ago    Answers:  5   Viewed   40 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:

    [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] => 




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

And you can use it like this:

  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

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
    $f = fopen('php://output', 'w');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
Wednesday, March 31, 2021
answered 8 Months ago

You could try to change the MIME type to

header('Content-type: text/csv');
Wednesday, March 31, 2021
answered 8 Months ago

You'd want something like this:

$csvName = "export.csv"
$sqlQuery = 'select * from sqlserver_table';
$sqlRresult = odbc_exec($conMsSql, $sql);

$fp = fopen(csvName , 'w');

while ($export = odbc_fetch_array($sqlRresult)) {
    if (!isset($headings))
        $headings = array_keys($export);
        fputcsv($fp, $headings, ',', '"');
    fputcsv($fp, $export, ',', '"');
Saturday, May 29, 2021
answered 5 Months ago

As mentioned in "GitHub API - write to repo", you would need to create a blob.

You can see an example in KnpLabs/php-github-api/test/Github/Tests/Api/GitData/BlobsTest.php#L53-L68

(I am using KnpLabs/php-github-api, since ornicar/php-github-api is deprecated and refers to it)

 * @test
public function shouldCreateBlob()
    $expectedValue = array('blob' => 'some data');
    $data = array('content' => 'some cotent', 'encoding' => 'utf8');

    $api = $this->getApiMock();
        ->with('repos/l3l0/l3l0repo/git/blobs', $data)

    $this->assertEquals($expectedValue, $api->create('l3l0', 'l3l0repo', $data));

There is no filename yet: you upload content;

To create a file though, as shown in this example, you would still need to:

  • get the SHA the current master branch points to
  • fetch the tree this SHA belongs to
  • create a new tree object with the new blob, based on the old tree
  • create a new commit object using the new tree and point its parent to the current master
  • finally update the heads/master reference to point to the new commit
Saturday, May 29, 2021
answered 5 Months ago

I got it. This is not my own work. I got some codes, combined them and modified to this code. However, finally, it worked.

print 'Proceeding'

import email
import getpass
import imaplib
import os
import sys

userName = ''
passwd = 'yourpassword'
directory = '/full/path/to/the/directory'

detach_dir = '.'
if 'DataFiles' not in os.listdir(detach_dir):

    imapSession = imaplib.IMAP4_SSL('')
    typ, accountDetails = imapSession.login(userName, passwd)
    if typ != 'OK':
        print 'Not able to sign in!'
        raise'[Gmail]/All Mail')
    typ, data =, 'ALL')
    if typ != 'OK':
        print 'Error searching Inbox.'

    for msgId in data[0].split():
        typ, messageParts = imapSession.fetch(msgId, '(RFC822)')
        if typ != 'OK':
            print 'Error fetching mail.'

        emailBody = messageParts[0][1]
        mail = email.message_from_string(emailBody)
        for part in mail.walk():
            if part.get_content_maintype() == 'multipart':
            if part.get('Content-Disposition') is None:
            fileName = part.get_filename()

            if bool(fileName):
                filePath = os.path.join(detach_dir, 'DataFiles', fileName)
                if not os.path.isfile(filePath) :
                    print fileName
                    fp = open(filePath, 'wb')

    print 'Done'

except :
    print 'Not able to download all attachments.'
Wednesday, August 4, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :