How to save the fetch result to a txt and then download?

Asked

Viewed 300 times

0

I have following code

$arquivo = fopen("descricao.txt","w");

while($dados = $cod_user->fetch_array()){ 
$bla = $dados['descricao'];
echo $dados['descricao'];

fwrite($arquivo,$bla);

How I choose the directory to save the file and then download?

  • What do you mean by "... appearing a window asking the user for the location?" ? What location is this? From the file?

  • when generating the download file

1 answer

0

It is not very clear your intent, but I think what you want is to fetch data from the database and write it to a txt file on the server. So if that’s it, the windpipe goes down:

<?php

$conn = new mysqli ("localhost", "USUARIO", "SENHA", "nomeDB");

$query = ("SELECT coluna FROM suaTabela");
$result = mysqli_query($conn, $query);

while($row = mysqli_fetch_assoc($result)) {
    $conteudo=$conteudo.chr(10).$row['n']."\r\n";
}

mysqli_close($conn);

$arquivo="linhas.txt";

file_put_contents($arquivo, $conteudo); 

/*
==========================================================================
Se o arquivo (linhas.txt) não existir, o arquivo é criado.
Do contrário, o arquivo é sobrescrito,
a não ser que o parâmetro FILE_APPEND seja definido e
nesse caso acrescenta os dados ao arquivo ao invés de sobrescrevê-lo.
Dessa forma acrescente esse parâmetro na linha file_put_contents, que
deverá ficar assim:  file_put_contents($arquivo, $conteudo, FILE_APPEND);
==========================================================================
*/

/* pode usar o trecho abaixo ao invés de file_put_contents
   $arq = fopen($arquivo,"w");
   fwrite($arq,$conteudo);
   fclose($arq);
*/

?>

And to download the file after it is recorded, add this snippet before the PHP closing tag to open the download options window.

header('Content-type: octet/stream');
header('Content-disposition: attachment; filename="'.$arquivo.'";'); 
readfile($arquivo);

file_put_contents http://php.net/manual/en/function.file-put-contents.php

fwrite http://php.net/manual/en/function.fwrite.php

Browser other questions tagged

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