如何将此代码的输出保存到文件中? (PHP)
问题描述:
此代码,通过一些MySQL表圈:如何将此代码的输出保存到文件中? (PHP)
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 />';
}
}
如何使它输出到一个文件? (只是表名和列名)
答
你可以使用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查询预处理语句。
+1
谢谢,它工作。 –
使用[fopen()](http://php.net/manual/en/function.fopen.php)在foreach循环之前打开一个用于写入的模式(模式'w')使用[fwrite()](http://php.net/manual/en/function.fwrite.php)写入foreach循环内的文件;使用[fclose()](http://php.net/manual/en/function.fclose.php)在您的foreach循环后关闭文件 –