Sample code for 30+ languages & platforms
PHP

Create CSV File

See more CSV Examples

Demonstrates how to create a new CSV file with some simple content.

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\Csv;

// This sample code creates a new CSV file (sample.csv)
// that contains this content:
//
// year,color,country,food
// 2001,red,France,cheese
// 2005,blue,"United States",hamburger

$csv = new Csv();

// Indicate that the 1st row
// should be treated as column names:
$csv->HasColumnNames = true;

$csv->SetColumnName(0, 'year');
$csv->SetColumnName(1, 'color');
$csv->SetColumnName(2, 'country');
$csv->SetColumnName(3, 'food');

$csv->SetCell(0, 0, '2001');
$csv->SetCell(0, 1, 'red');
$csv->SetCell(0, 2, 'France');
$csv->SetCell(0, 3, 'cheese');

$csv->SetCell(1, 0, '2005');
$csv->SetCell(1, 1, 'blue');
$csv->SetCell(1, 2, 'United States');
$csv->SetCell(1, 3, 'hamburger');

// Write the CSV to a string and display:
$csvDoc = $csv->SaveToString();
echo $csvDoc, "\n";

// Save the CSV to a file:
try {
    $csv->SaveFile('out.csv');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
}