这个问题在这里已有答案:
我有PHP代码读取多个TXT文件,并允许用户搜索指定的字符串,并在系统读取所有文本文件后,根据用户输入,系统将显示包含用户请求的文件名。
问题是,当我运行代码时,网页显示:
警告:fopen()期望参数1是有效路径,第11行的C:\ xampp \ htdocs \ readfiletest \ index.php中给出的数组
警告:fclose()要求参数1为资源,在第64行的C:\ xampp \ htdocs \ readfiletest \ index.php中给出布尔值
我的代码中的错误以及如何修复它?
<?php
//path to directory
$directory = $_SERVER['DOCUMENT_ROOT']."/readfiletest/";
$txts= glob($directory. "*.txt") or DIE("Unable to open $directory");
$myFileLink = fopen($txts, 'r');
$line = 1;
if(isset($_POST["search"]))
{
$search =$_POST['name'];
while(!feof($myFileLink))
{
$myFileContents = fgets($myFileLink);
if( preg_match_all('/('.preg_quote($search,'/').')/i', $myFileContents, $matches))
{
foreach($matches[1] as $match)
{
echo "Found $match on Line $line";
}
}
++$line;
}
}
fclose($myFileLink);
?>
<html>
<head>
</head>
<meta http-equiv="Content-Language" content="ar-sa">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<body>
<form action="index.php" method="post">
<p>enter your string <input type ="text" id = "idName" name="name" /></p>
<p><input type ="Submit" name ="search" value= "Search" /></p>
</form>
</body>
</html>
如果你只想解决问题,你需要这样的东西:
$directory = $_SERVER['DOCUMENT_ROOT']."/readfiletest/";
$txts= glob($directory. "*.txt") or DIE("Unable to open $directory");
Foreach ($txts as $txt){
$myFileLink = fopen($txt, 'r');
// .... And so on..
这将打开一个文件并搜索它们。
就像是:
$directory = $_SERVER['DOCUMENT_ROOT']."/readfiletest/";
$txts= glob($directory. "*.txt") or DIE("Unable to open $directory");
Foreach ($txts as $txt){
$myFileContents = file_get_contents($txt);
If(preg_match('/('.preg_quote($search,'/').')/i', $myFileContents, $matches)){
// Here we know there is a match in the file, if there is no match there is no need to search each line
我建议使用symfony中的“Finder”组件
http://symfony.com/doc/current/components/finder.html
https://github.com/symfony/finder
在查找器中它应该是这样的
$finder=new Finder();
$finder->in($directory)->files()->name('*.txt')->contains($search);
// and it's all - simple - isn't it ?
//to see all result you do
foreach ($finder as $file) {
$contents = $file->getContents();
// ...
}
您可以轻松使用它而无需整个symfony(通过composer安装)。
我知道这对你来说可能看起来有点复杂,但相信我 - 这是一个用于搜索文件的最佳php解决方案,它绝对值得学习