Skip to content

Exporter

Mehdi Bounya edited this page Jul 14, 2018 · 1 revision

An exporter is a class that will take data validated by the Validator and export it. Currently, there are two exporters ExportCSV to save data to a CSV file and ExportDB to save data to a database.

All exporters must extend the \PHPForms\Exporter abstract class.

Content

Maps

Maps are a way to map field names to different columns, you can set a map by passing an array to the setMap() method. The array should look like this:

$map = [
    'field_name' => 'column_name',
];

Exporting to CSV

You can export submitted data to a CSV file using \PHPForms\ExportCSV:

// This is the data to export, usually you will want to use the getValidData method
$data = $validator->getValidData();

// A map is optional
$map = [];

$csv = new \PHPForms\ExportCSV('path/to/file.csv', $data, $map);

// We can add additional data
$csv->addData('field_name', 'value');
// If a value for first_name already exists it will be replaced with Mehdi
$csv->addData('first_name', 'Mehdi');

// Let's say we want to map data to different columns, we can use the setMap() method
$map = [
    'first_name' => 'First name',
    'last_name'  => 'Last name',
    'message'    => 'Comment',
];

$csv->setMap($map);

// And then we export the data
if ($csv->export()) {
    echo "Data exported";
} else {
    echo "Failed to export";
}

Exporting to database

You can export submitted data to a database using \PHPForms\ExportDB, it has the same methods as ExportCSV but to initialise it you should:

$db = new \PHPForms\ExportDB($pdo, $table_name, $data, $map);

$pdo is your PDO instance, and $table_name is your table's name.

There is one extra method you can use which is setTable($table_name).

Custom exporter

You can create a custom exporter by simply extending the \PHPForms\Exporter abstract class

Clone this wiki locally