$myfile = fopen("lastupdate.txt", "r") 或 die("无法打开文件!");
echo fread($myfile,filesize("lastupdate.txt"));
fclose($myfile);
这是我的 WordPress 插件中的 php 代码。当我更新网站 20 次时,加载单个页面大约需要 20 秒。如果没有这 3 行代码,加载页面只需要 1 秒。
你能告诉我为什么这么慢吗?
我想使用文本文件来存储字符串(2000 个字符)。 在我的测试中,里面只有一个“hello world”,而且仍然需要一秒钟。我该如何解决这个问题?
非常感谢。
最佳答案
如果您只想将文件的内容获取到字符串中,请使用 file_get_contents()因为它有更好的性能
file_get_contents()是将文件内容读入字符串的首选方法。如果您的操作系统支持,它将使用内存映射技术来提高性能。
在当前上下文中,
<?php
$myfile = fopen("lastupdate.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("lastupdate.txt"));
fclose($myfile);
?>
可以替换为readfile() ,这将读取文件并将其通过一个命令发送到浏览器
<?php
readfile("lastupdate.txt");
?>
这本质上是相同的
<?php
echo file_get_contents("lastupdate.txt");
?>
除了file_get_contents()对于大文件可能会导致脚本崩溃,而 readfile()不会。
关于php - 多次刷新页面时读取文件变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42425414/