Pass multidimencional array by POST, and use it in PHP to export in CSV

Asked

Viewed 42 times

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:

inserir a descrição da imagem aqui

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:

inserir a descrição da imagem aqui

1 answer

1


I believe the error occurs because you pass a string in the post and not an array, so php could not identify that it is an array when it receives the data. There is a function that serves exactly to solve this problem, serialize.

// formulario.php
<?php $retorno = [
        [
            'id' => 1,
        ],
        [
            'id' => 2,
        ],
    ];
?>

<html>
    <form action="export.php" method="post" enctype="multipart/form-data" >
        <div class="col pt-4 mt-2">
            <input name="acao" value="export" hidden/>
                <input type="hidden" name="dados" value="<?php echo htmlentities(serialize($retorno));?>" />
            <input class="btn btn-sm btn-primary font-weight-bold" type="submit" value="Exportar"/>
        </div>
    </form>
</html>

// export.php
<?php

var_dump(unserialize($_POST['dados']));die;

Upshot:

export.php:3:
array (size=2)
  0 => 
    array (size=1)
      'id' => int 1
  1 => 
    array (size=1)
      'id' => int 2
  • It worked! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.