0
It’s been a while since I’ve been banging my head to solve this problem. I need to pass a multidimensional array by POST to use it in PHP to export a CSV file.
Let’s go to the codes!
In the form I have it:
<form action="export.php" method="post" enctype="multipart/form-data" >
<div class="col pt-4 mt-2">
<input name="acao" value="export" hidden/>
<?php foreach ($retorno as $item): ?>
<input type="text" name="dados[]" value="<?php print_r($item);?>" hidden/>
<?php endforeach ?>
<input class="btn btn-sm btn-primary font-weight-bold" type="submit" value="Exportar"/>
</div>
</form>
The $retorno
is at the following value (which is coming from a code further up):
Array
(
[0] => Array
(
[id] => 10
[mat_indicador] => 8646
[nome_indicado] => nomeIndicado
[tel_indicado] => 999999999
[tel_indicado_op] =>
[cpf_indicado] => 99999999999
[status] => 0
[sobrenome_indicado] => sobrenometeste
[setor] => D.P.
[nome] => teste
[data_criado] => 2019-10-09 12:58:14
)
[1] => Array
(
[id] => 11
[mat_indicador] => 3696
[nome_indicado] => nomeIndicado
[tel_indicado] => 999999999
[tel_indicado_op] =>
[cpf_indicado] => 99999999999
[status] => 0
[sobrenome_indicado] => sobrenometeste
[setor] => Fisioterapia
[nome] => teste
[data_criado] => 2019-10-09 13:23:48
)
)
At the beginning of the file export.php
I have the following code:
$retorno = $_POST['dados'];
echo "<pre>";
print_r($_POST['dados']);
echo "</pre>";
die();
But it prints the indexes as string:
The code I’m using to export is this:
function export_data_to_csv($retorno, $filename='export', $delimiter = ';', $enclosure = '"'){
// Tells to the browser that a file is returned, with its name : $filename.csv
header("Content-disposition: attachment; filename=$filename.xls");
// Tells to the browser that the content is a csv file
header("Content-Type: application/x-msexcel;charset=UTF-8");
// I open PHP memory as a file
$fp = fopen("php://output", 'w');
// Insert the UTF-8 BOM in the file
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
// I add the array keys as CSV headers
fputcsv($fp,array_keys($retorno[0]), $delimiter, $enclosure);
// Add all the data in the file
foreach ($retorno as $key => $fields) {
fputcsv($fp, $fields, $delimiter, $enclosure);
}
// Close the file
fclose($fp);
// Stop the script
die();
}
export_data_to_csv($retorno);
And it gives problem because the array_keys
expects an array, but a string is coming.
The mistakes they make are these:
It worked! Thank you very much!
– Sumback