print PHP result in multiple TXT files

1

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

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

(per line)

I would like to print this php result in multiple TXT files with no more than 18,000 lines per file.

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

Can anyone help me?

    
asked by anonymous 25.09.2017 / 21:30

2 answers

3

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 already exist it creates the file.

     

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

With the 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;
}
    
25.09.2017 / 23:07
1

Once you get the array with the database information, use the array_chunk() to divide this array by an arbitrary number (in this example it is the two).

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

To scan files in a folder on the server 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);
}

Calling array_chunk() $arquivos will have this structure.

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

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

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

)
    
25.09.2017 / 21:43