PHP写入文件 [英] PHP write to file

查看:72
本文介绍了PHP写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一些我用来将地图数组翻译"为SQL代码的代码,以便在更新游戏地图后可以轻松地更新数据库.如您所见,它会将SQL代码打印到屏幕上,以便我复制和粘贴它.

below is some code I am using to "translate" a map array into SQL code so I can easily update my database when I have updated my game map. As you can see it prints out the SQL code onto the screen so I can copy and paste it.

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

As my maps will get bigger this will become inefficient as it will crash the browser due to mass output, so instead I am wondering if it is possible to make it create a .txt file and write all of the data to it instead of printing onto the screen?

<?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);
}
}
}
?>

推荐答案

那应该很简单.添加

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

到脚本的开头.

添加

fclose($f);

最后,您的脚本将干净地关闭文件句柄(即使句柄将自动关闭,终止脚本也很好).

to the end fo your script to cleanly close the file handle (good pratice even though handles would be closed the the terminating script automatically).

然后将所有echoprint都更改为

fwrite($f, '<<your string>>');

这样,您甚至可以使用压缩流包装器即时压缩数据如果数据量真的很大.

That way you can even compress the data on the fly using a compression stream wrapper if amnount of data gets really large.

这篇关于PHP写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆