Format data and save to txt with php

Asked

Viewed 974 times

1

The goal is to extract data from the base and save in txt file... The script works correctly when I enter only $log (name) on the line

if (!fwrite($savelog, $log))

in an attempt to add $log2 (numero)

if (!fwrite($savelog, $log, $log2))

error

( Warning: fwrite() expects Parameter 3 to be long, string Given in)

what solution to store the two data in txt with its proper formatting (str_pad) ?

<?php

include "conexao.php";

$querymail = mysql_query("select nome,numero from listagem");
fopen("listar.txt", "w+");
while($data = mysql_fetch_array($querymail)) {
$log = str_pad($data[nome], 30, " ", STR_PAD_RIGHT);
$log2 = str_pad($data[numero], 30, "0", STR_PAD_RIGHT);
if (!$savelog = fopen('listar.txt', "a")) 
{ exit; }
if (!fwrite($savelog, $log, $log2))
{ exit; fclose($savelog); }
}
?>
<a href="listar.txt">Download</a>

1 answer

0


I don’t understand your use of fwrite, in accordance with documentation the use is this:

int fwrite ( resource $handle , string $string [, int $length ] )

The third parameter is expected an integer number and not a string.

If the argument $length is used, the writing of the document will stop after that length bytes have been written or the end of the string is reached, whichever comes first.

In other words, it is a "writing limiter".

If your goal is to record the content of $log2 = str_pad($data[numero], 30, "0", STR_PAD_RIGHT); no . txt do so:

if ($savelog = fopen('listar.txt', "a")) {
    fwrite($savelog, $log);
    fwrite($savelog, $log2);
    fclose($savelog);
}

Concatenating:

if ($savelog = fopen('listar.txt', "a")) {
    fwrite($savelog, $log . $log2);
    fclose($savelog);
}

Or with line break:

if ($savelog = fopen('listar.txt', "a")) {
    fwrite($savelog, $log . PHP_EOL);
    fwrite($savelog, $log2);
    fclose($savelog);
}

Concatenating:

if ($savelog = fopen('listar.txt', "a")) {
    fwrite($savelog, $log . PHP_EOL . $log2);
    fclose($savelog);
}

Note that windows Notepad.exe requires r n to support view line breaks, the PHP_EOL functions as n in all modern operating systems.

  • 1

    The concatenation resulted in solution... Thanks!

Browser other questions tagged

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