webservice/bin/sql2csv.php
2017-02-28 12:26:29 +01:00

57 lines
1.3 KiB
PHP

<?php
require_once __DIR__ . '/../application/bin.bootstrap.php';
// --- Options
$displayUsage = false;
try {
$opts = new Zend_Console_Getopt(array(
'help|?' => "Displays usage information.",
'sqlfile=s' => "",
'csvfile=s' => "",
));
$opts->parse();
$optionsNb = count($opts->getOptions());
} catch (Zend_Console_Getopt_Exception $e) {
$displayUsage = true;
}
// --- Aide / Options
if (count($opts->getOptions())==0 || isset($opts->help)) {
$displayUsage = true;
}
// --- Usage
if ($displayUsage) {
echo "Génération d'un fichier CSV à partir d'un fichier SQL.\n";
echo $opts->getUsageMessage();
exit;
}
use League\Csv\Writer;
$sql = file_get_contents($opts->sqlfile);
//we fetch the info from a DB using a PDO object
$stmt = $conn->executeQuery($sql);
if ($stmt->rowCount() == 0) {
file_put_contents($opts->csvfile, "");
}
else {
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
// Create the CSV
$csv = Writer::createFromPath($opts->csvfile.'.tmp', 'w');
$csv->setNewline("\r\n");
$csv->setOutputBOM(Writer::BOM_UTF8);
// Insert the CSV header
$csv->insertOne(array_keys($rows[0]));
// Insert all data
$csv->insertAll($rows);
// Set the real name of file
rename($opts->csvfile.'.tmp', $opts->csvfile);
}