print PHP result on multiple TXT files

Asked

Viewed 270 times

1

I have a PHP file that does a database search and generates all Urls, stored in the database in a single file.

www.url1.com
www.url2.com
Etc...

(per line)

Would like to print out this result, from php, in multiple TXT files with a maximum of 18,000 lines per file.

Ex: arquivo1.txt arquivo2.txt Etc...

Someone can help me?

  • I think what you want is this: https://www.w3schools.com/php/php_file_create.asp

  • If any answer has served you read this post https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

2 answers

2


Assuming Mysqli

$conn = new mysqli($servername, $username, $password, $dbname);

$query = "SELECT nome_coluna FROM nome_tabela";
$result = mysqli_query($conn,$query);

$k=1;
$i=1;

while($row = mysqli_fetch_assoc($result)) {
    $res = $row["nome_coluna"]."\n";
    file_put_contents("arquivo".$i.".txt", $res, FILE_APPEND);
    //nos multiplos de 18000 muda o nome do arquivo acima
    if (($k%18000)==0){
        $i=$i+1;
    }

    $k=$k+1;
}

put_contents - writes a string to a file, if this file does not yet exist it creates the file.

FILE_APPEND - adds the data to the file instead of overwriting it.

With already discontinued Mysql: - as requested in the comment

$conn = mysql_connect("localhost","USUARIO","SENHA");

mysql_select_db("nome_DB", $conn);

$query = mysql_query("SELECT nome_coluna FROM nome_tabela");

$k=1;
$i=1;

while($row = mysql_fetch_array($query)){
    $res = $row["nome_coluna"]."\n";
    file_put_contents("arquivo".$i.".txt", $res, FILE_APPEND);

    if (($k%18000)==0){
        $i=$i+1;
    }

    $k=$k+1;
}
  • Good Leo, get the same example with Mysql?

  • 1

    @Marcelo reply with Mysql also

1

After picking up the array with the database information, use the function array_chunk() to divide this array by an arbitrary number (in this example is two).

implode() will format each element of the array as a line in the file, as the separator is \r\n.

To scrutinize the files in some server folder you can use file_put_contents(). Another option is the combination fopen(), fwrite() and fclose().

$arr = array('url1', 'url2', 'url3', 'url4', 'url5', 'url6');

$arquivos = array_chunk($arr, 2);


$i=1;
foreach ($arquivos as $item) {
    $str = implode("\r\n", $item);
    file_put_contents($i++.'.txt', $str);
}

By calling array_chunk() $arquivos will have that manure.

Array
(
    [0] => Array
        (
            [0] => url1
            [1] => url2
        )

    [1] => Array
        (
            [0] => url3
            [1] => url4
        )

    [2] => Array
        (
            [0] => url5
            [1] => url6
        )

)
  • Just correction, it would be fopen() and not fopne(), right?

  • 1

    @Tiagoboeing, correct, corrected now. Thank you.

Browser other questions tagged

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