如何将此代码的输出保存到文件中? (PHP)

时间:2016-05-14 19:46:16

标签: php mysql file

这段代码循环遍历一些mysql表:

foreach($tables as $table)
{
echo "<h2>" . $table[0] . "</h2>";
$query = "DESCRIBE " . $table[0];
$result = $mysqli->query($query);

$columns = $result->fetch_all();

foreach($columns as $column)
{
    echo $column[0]. '<br />';
}
}

如何将其输出到文件? (只是表名和列名)

1 个答案:

答案 0 :(得分:0)

您可以使用fopen和fwrite PHP函数来执行此操作。

这将是这样的:

<?php

// Here we create a file handler
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");

foreach($tables as $table)
{
    echo "<h2>" . $table[0] . "</h2>";
    // Here, we write the value of $table[0] and a new line in the file
    fwrite($myfile, "Table " . $table[0] . "\n");

    $query = "DESCRIBE " . $table[0];
    $result = $mysqli->query($query);

    $columns = $result->fetch_all();

    foreach($columns as $column)
    {
        echo $column[0]. '<br />';
        fwrite($myfile, " - " . $column[0] . "\n");
    }
}
fclose($myfile);

?>

注意:我强烈建议您为SQL查询使用预准备语句。