PHP写入文件

Rya*_*yan 2 php file

下面是我用来将地图数组"翻译"成SQL代码的一些代码,这样当我更新我的游戏地图时,我可以轻松更新我的数据库.正如您所看到的,它将SQL代码打印到屏幕上,以便我可以复制并粘贴它.

随着我的地图变得越来越大,这将变得效率低下,因为它会因为大量输出而导致浏览器崩溃,所以我想知道是否可以创建.txt文件并将所有数据写入其中而不是打印到屏幕?

<?php
if (isset($_POST['code'])){
$map = $_POST['code'];
$map = preg_replace("/,\\s*}/i", "}", $map);
$map = str_replace("{", "[", $map);
$map = str_replace("}", "]", $map);
$map = json_decode('[' . $map . ']');

$arrayCount1 = 0;
$arrayCount2 = -1;

$H = sprintf('%05d', 00000);
$V = sprintf('%05d', 00000);
$id = 1;

echo "INSERT INTO `map` (`id`, `horizontal`, `verticle`, `image`) VALUES" . "<br />";

for ($count1 = 0; $count1 < sizeof($map[0]); $count1++){
$arrayCount2++;
$arrayCount1 = 0;
$V = sprintf('%05d', $V + 1);
$H = sprintf('%05d', 00000);

for ($count2 = 0; $count2 < sizeof($map); $count2++){
echo "(" . $id . ", '" . $H . "', '" . $V . "', '" . $map[$arrayCount1][$arrayCount2] . "')," . "<br />";
$arrayCount1++;
$id++;
$H = sprintf('%05d', $H + 1);
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)

Ste*_*rig 10

这应该很简单.加

// second parameter 'a' stands for APPEND
$f = fopen('/path/to/the/file/you/want/to/write/to', 'a');
Run Code Online (Sandbox Code Playgroud)

到脚本的开头.

fclose($f);
Run Code Online (Sandbox Code Playgroud)

到最后你的脚本干净地关闭文件句柄(好的实践,即使句柄将自动关闭终止脚本).

并且改变所有echo的和prints到

fwrite($f, '<<your string>>');
Run Code Online (Sandbox Code Playgroud)

编辑:

这样,如果数据量非常大,您甚至可以使用压缩流包装器动态压缩数据.


sou*_*rge 7

有一种更简单的方法:

ob_start();
# Your code here ...
file_put_contents('yourfile.txt', ob_get_clean());
Run Code Online (Sandbox Code Playgroud)