我有一个html页面,其中有一个表单。 我的index.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="result.php" method="post">
<input type="text" name="searchVal" placeholder="Type here">
<input type="submit" value="click on me!">
</form>
</body>
</html>
我有一个包含大量数据的txt文件。 我的php文件读取txt文件getdata.php如下
我的getdata.php
<?php
$file = fopen("file.txt", "r");
while(!feof($file))
{
$line = fgets($file); //utf8_encode(fgets($file));
$piece = explode("=", $line);
//each line in the file is separated by = sign.like abcd=pouy.
//So i have $piece[0] and $piece[1]
}
fclose($file);
?>
现在当我提交表格时,它会转到result.php 我的result.php
<?php include('getdata.php') ?> //getdata.php reads the file.txt
<?php
$val=$_POST["searchVal"];
$atoms = explode(" ", $val);
foreach($atoms as $result) {
// heremy code goes
// here I need data from file.txt for which
// I need to include getdata.php which reads the file
}
?>
现在,当我以这种方式工作时,执行时间变得非常高,因为我每次提交时都转到result.php,它加载了getdata.php(每次读取大文件.txt)。
如何以这样的方式实现相同的东西,以便getdata.php只加载一次?
我需要我的索引页面是html。我无法用.php扩展来实现它。这就是限制。
答案 0 :(得分:2)
这是PHP缓存。 Symfony2方式,减去天赋。
$lifetime = 3600;
$cache = 'data.cache.php';
if (!file_exists($cache) || time() - filemtime($cache) > $lifetime) {
$pieces = array();
$file = fopen("file.txt", "r");
while(!feof($file)) {
$line = fgets($file); //utf8_encode(fgets($file));
$pieces[] = explode("=", $line);
}
// Edit: moved out of loop.
file_put_contents($cache, sprintf('<?php $pieces = %s;', var_export($pieces, true)));
} else {
include_once($cache);
}