I’m having trouble exporting CSV file in PHP

Asked

Viewed 18 times

-1

Can you help me gentlemen... I’m with a code that is exporting data to CSV, however, the body of the request is coming out together in the file. I would like to export only the data, without the entire post. It follows below my code and how is coming the CSV:

list_users.php file

header("Content-Type: text/html; charset=ISO-8859-1",true);

if ($_POST['action']){
    if (isset($_POST["export_cli"])){
        $headers = ['ID', 'USUARIO', 'PERFIL', 'STATUS'];

        $dados = [
            [
                'ID' => '2',
                'USUARIO' => 'admin',
                'PERFIL' => 'ADMIN',
                'STATUS' => 'ATIVADO',
            ],
            [
                'ID' => '3',
                'USUARIO' => 'admin',
                'PERFIL' => 'ADMIN',
                'STATUS' => 'ATIVADO',
            ],
            [
                'ID' => '22',
                'USUARIO' => 'sittms',
                'PERFIL' => 'ADMIN',
                'STATUS' => 'ATIVADO',
            ],
            [
                'ID' => '341',
                'USUARIO' => 'DESATIVADO FCZGPMQ',
                'PERFIL' => 'ADMIN',
                'STATUS' => 'ATIVADO',
            ],
        ];

        $arquivo = fopen('php://output', 'w');

        fputcsv($arquivo , $headers);

        foreach ($dados as $chave => $valor) {
            $ID[$chave]  = $valor['ID'];
            $USUARIO[$chave] = $valor['USUARIO'];
            $PERFIL[$chave] = $valor['PERFIL'];
            $STATUS[$chave] = $valor['STATUS'];
        }

        foreach ($dados as $linha ){
            fputcsv($arquivo, $linha);
        }

        fclose($arquivo);
        header('Content-Type: application/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=Usuarios.csv');
    }
}


?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="css/css.css" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>FirstData</title>
 <script type="text/javascript">
        
 </script>
</head>

<body>
<center>
<div id="wrap">

    <div id="geral">
 
    <div style="clear:both; padding-bottom:10px;"></div>
         
             <table width="500" align="center">
                  <tr>
                    <td colspan="2" align="center" class="titulos">Busca de Usuarios</td>
                  </tr> 
            </table>
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="fDados" id="formulario">
            <input type="hidden" name="action" value="1" />
                <table width="500" align="center">
                      <tr>
                        <td width="150" align="center" class="titulos2"><strong>ID Usuário</strong></td>
                        <td width="250" class="bg"><input name="busca_id_lgn" id="busca_id_lgn" style="width:200px;"  type="text" value=""/></td>
                      </tr>
                      <tr>
                        <td width="150" align="center" class="titulos2"><strong>Usuário</strong></td>
                        <td width="250" class="bg"><input name="busca_login" id="busca_login" style="width:200px;"  type="text" value=""/></td>
                      </tr>
                      <tr>
                        <td colspan="2" width="250" align="right" >
                            <input name="busca_cli" id="busca_cli" type="submit" value="Busca Usuario" class="button"/>
                            <input name="export_cli" id="export_cli" type="submit" value="Exportar Usuarios" class="button"/>
                        </td>
                      </tr>
                </table>
            </form>
            
            <table width="500" align="center">
                  <tr>
                    <td align="center" class="titulos2"><strong>&nbsp;&nbsp;ID</strong></td>
                    <td align="center" class="titulos2"><strong>&nbsp;&nbsp;Usuario</strong></td>
                    <td align="center" class="titulos2"><strong>&nbsp;&nbsp;Perfil</strong></td>
                    <td align="center" class="titulos2"><strong>&nbsp;&nbsp;Status </strong></td>
                    <td align="center" class="titulos2"><strong>&nbsp;&nbsp;</strong></td>
                  </tr>
                  
                  <?php //Resultado
                  
$count = 0;
            if($oksql){

                  while ($row = $conn->fetch()) {
                    $count++;
                    ?>
                     <tr>
                    <td align="center" class="titulos3"><strong>&nbsp;<?=$row['PKNI_LGN_ID'];?></strong></td>
                    <td align="center" class="titulos3"><strong>&nbsp;<?=$row['ATSV_LGN_LOGIN'];?></strong></td>
                    <td align="center" class="titulos3"><strong>&nbsp;<?=$row['ATSV_GAC_DESCRIPTON'];?></strong></td>
                    <td align="center" class="titulos3"><strong>&nbsp;<?=$row['ATIVO'];?></strong></td>
                    <td align="center" class="titulos3">
                        <strong>&nbsp;&nbsp;<a href="form_user.php?id=<?=$row['PKNI_LGN_ID'];?>"><img src="img/editar.gif" border="0" /></a>
                        </strong>
                    </td>
                  </tr>
                  <?php
                  }
            }
                  ?>
            </table>
            
    </div>
</div>

<div id="overlay"></div>
<div id="report"></div>

</body>
</html>

o arquivo esta saindo assim:

ID,USUARIO,PERFIL,STATUS
2,admin,ADMIN,ATIVADO
3,admin,ADMIN,ATIVADO
22,sittms,ADMIN,ATIVADO
341,"DESATIVADO FCZGPMQ",ADMIN,ATIVADO

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="css/css.css" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>FirstData</title>
 <script type="text/javascript">
        
 </script>
</head>

<body>
<center>
<div id="wrap">

    <div id="geral">
 
    <div style="clear:both; padding-bottom:10px;"></div>
         
             <table width="500" align="center">
                  <tr>
                    <td colspan="2" align="center" class="titulos">Busca de Usuarios</td>
                  </tr> 
            </table>
            <form action="/teste/list_users.php" method="post" name="fDados" id="formulario">
            <input type="hidden" name="action" value="1" />
                <table width="500" align="center">
                      <tr>
                        <td width="150" align="center" class="titulos2"><strong>ID Usuário</strong></td>
                        <td width="250" class="bg"><input name="busca_id_lgn" id="busca_id_lgn" style="width:200px;"  type="text" value=""/></td>
                      </tr>
                      <tr>
                        <td width="150" align="center" class="titulos2"><strong>Usuário</strong></td>
                        <td width="250" class="bg"><input name="busca_login" id="busca_login" style="width:200px;"  type="text" value=""/></td>
                      </tr>
                      <tr>
                        <td colspan="2" width="250" align="right" >
                            <input name="busca_cli" id="busca_cli" type="submit" value="Busca Usuario" class="button"/>
                            <input name="export_cli" id="export_cli" type="submit" value="Exportar Usuarios" class="button"/>
                        </td>
                      </tr>
                </table>
            </form>
            
            <table width="500" align="center">
                  <tr>
                    <td align="center" class="titulos2"><strong>&nbsp;&nbsp;ID</strong></td>
                    <td align="center" class="titulos2"><strong>&nbsp;&nbsp;Usuario</strong></td>
                    <td align="center" class="titulos2"><strong>&nbsp;&nbsp;Perfil</strong></td>
                    <td align="center" class="titulos2"><strong>&nbsp;&nbsp;Status </strong></td>
                    <td align="center" class="titulos2"><strong>&nbsp;&nbsp;</strong></td>
                  </tr>
                  
                  <br />
<b>Notice</b>:  Undefined variable: oksql in <b>C:\xampp\htdocs\teste\list_users.php</b> on line <b>115</b><br />
            </table>
            
    </div>
</div>

<div id="overlay"></div>
<div id="report"></div>

</body>
</html>

1 answer

0

What happens in this case is that after generating the attachment and changing the headers of the request to download the processing of the page is not terminated, so comes out a file with CSV + HTML that would be rendered by the browser.

This can be solved by terminating the script execution after attaching the file to the return header. Your code would look like this:

fclose($arquivo);
 header('Content-Type: application/csv; charset=utf-8');
 header('Content-Disposition: attachment; filename=Usuarios.csv');
 exit();

Browser other questions tagged

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