John
John

Reputation: 43

How to output text to file?

Here's my current code:

$link = mysqli_connect("localhost", "username", "password", "database");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT id, title FROM titles WHERE type = 'movie' ORDER BY id ASC";

if ($result = mysqli_query($link, $query)) {

    while ($row = mysqli_fetch_assoc($result)) {
        printf ("%s-%s\n", $row["id"], $row["title"]);
    }

    mysqli_free_result($result);
}

mysqli_close($link);

Using printf is correctly printing all the rows from my MySQL table.

However, instead of printing it, I want to write it to a text file. Is this possible to do with printf or should I be doing something else?

Upvotes: 0

Views: 162

Answers (3)

Barmar
Barmar

Reputation: 780724

Use fprintf(). It works just like printf(), but prints to a file stream.

if ($result = mysqli_query($link, $query)) {
    if ($fp = fopen("filename.txt", "w")) {
        while ($row = mysqli_fetch_assoc($result)) {
            fprintf ($fp, "%s-%s\n", $row["id"], $row["title"]);
        }
        fclose($fp);
    }

    mysqli_free_result($result);
}

Upvotes: 0

Ramu Manavalan
Ramu Manavalan

Reputation: 51

fprintf used to write to the file file_put_contents also works

  $fp = fopen('output.txt', 'w');
  $in = 'text';
  fprintf($fp, '%s', $in);

Upvotes: 1

Lohmar ASHAR
Lohmar ASHAR

Reputation: 1761

if you want to write it to the disk, on the server, you should look into fopen(), fwrite() and fclose()

also you could use file_put_contents, but that would require you to prepare all the content before writing it to the file (which could lead to high memory usage if you have lots of records) or if you go with the "append" mode, writing 1 line at a time, you'll have all the overhead of opening and closing the file each time

if you want to make the browser download it, instead of just showing the content, then you need to add a header to the response

header('Content-Disposition: attachment; filename="'.$filename.'"');

preferably adding some content type before it. for example, in your case:

header('Content-type: text/plain');

Upvotes: 2

Related Questions