peace_love
peace_love

Reputation: 6461

How can I create a CSV file in a directory and store data from my loop in a proper format?

I want to create a CSV file from my data. This is my loop:

foreach($animals as $row) {
    $row['species'];
    $row['name'];
    $row['size']
}

This is how I create my CSV. So far this works:

$country = 'africa';

$newFileName = './files/'.$country.".csv";
$newFileContent = 'here should be my content';                          

if(file_put_contents($newFileName,$newFileContent)!=false) {
    echo "File created (".basename($newFileName).")";
} else {
    echo "Cannot create file (".basename($newFileName).")";
}

But I have a problem to create from my loop in a proper CSV format.

With the help of a tutorial I tried this:

$country = 'africa';

$newFileName = './files/'.$country.".csv";
$newFileContent = $animals; 

foreach ($animals as $line) {
    fputcsv($newFileName,explode(',',$line));
}

if(file_put_contents($newFileName,$newFileContent)!=false) {
    echo "File created (".basename($newFileName).")";
} else {
    echo "Cannot create file (".basename($newFileName).")";
}

But this is not working.

Upvotes: 0

Views: 54

Answers (3)

andrew-caulfield
andrew-caulfield

Reputation: 2070

This is how I've always done it in the past.

$country = 'africa';

$fileName = "./files/" . $country . ".csv";

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");

$fh = @fopen( 'php://output', 'w' );

$headerDisplayed = false;

foreach ( $animals as $line ) {
    // Add a header row if it hasn't been added yet
    if ( !$headerDisplayed ) {
        // Use the keys from $line as the titles
        fputcsv($fh, array_keys($line));

        $headerDisplayed = true;
    }

    // Put the data into the stream
    fputcsv($fh, $line);
}
// Close the file
fclose($fh);
// Make sure nothing else is sent, our file is done
exit;

Upvotes: 1

mario.van.zadel
mario.van.zadel

Reputation: 2949

Regarding the first foreach loop in your question $animals is an array containing arrays with keys species, name and size.

So you have to change

foreach ($animals as $line){
   fputcsv($newFileName,explode(',',$line));
}

to

foreach ($animals as $line){
    fputcsv($newFileName, array($line['species'], $line['name'], $line['size']));
}

because $line is already an array and should be exploded.

Upvotes: 2

BaZ
BaZ

Reputation: 36

You need to open your file for writing first and grab the file handle:

$country = 'africa';

$newFileName = "./files/" . $country . ".csv";

$fileHandle = fopen($newFileName,"w"); // Open file for writing

foreach ($animals as $line){
  fputcsv($fileHandle, explode(',',$line));
}

fclose($fileHandle);  // Make sure we close file after finishing writing to it

Upvotes: 2

Related Questions