2017-02-23 64 views
1

$myfile = fopen("lastupdate.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("lastupdate.txt")); fclose($myfile);读取文件多次

刷新页面时慢这是我的WordPress插件我的PHP代码。当我更新网站20次时,大约需要20秒才能加载单个页面。如果没有这3行代码,它只需要1秒来加载页面。

你能告诉我为什么这么慢吗?

我想使用文本文件来存储一个字符串(2000个字符)。 在我的测试中,里面只有一个“hello world”,它仍然需要一秒钟。我该如何解决这个问题?

非常感谢。

回答

0

如果你只是想获得一个文件转换成字符串的内容,使用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()可能会导致s cript为大文件崩溃,而readfile()不会。

+1

谢谢:) :)更好地工作 – MasterOfDesaster