2016-06-12 69 views
1

我想让我的PHP脚本打开多个文本文档并阅读它们。打开php中的多个文件

我当前的脚本如下:

<?php 
 
\t //$searchthis = "ignore this"; 
 
\t $matches = array(); 
 
\t $FileW = fopen('result.txt', 'w'); 
 
\t $handle = @fopen("textfile1.txt", "r"); 
 
\t ini_set('memory_limit', '-1'); 
 
\t if ($handle) 
 
\t { 
 
\t \t while (!feof($handle)) 
 
\t \t { 
 
\t \t \t $buffer = fgets($handle); 
 
\t \t \t if(stripos($buffer, $_POST["search"]) !== FALSE) 
 
\t \t \t \t $matches[] = $buffer; 
 
\t \t } 
 
\t \t fwrite($FileW, print_r($matches, TRUE)); 
 
\t \t fclose($handle); 
 
\t } 
 
?>

我想给fopen像一堆文件,也许像他们的8个或更少。

我将如何打开并阅读所有这些文件?

任何帮助非常感谢!

+0

停止做'@ fopen'的'@'抑制任何错误,有可能是 - 与'fopen',错误是常见和重要的。你有什么自己尝试过的? – ceejayoz

+0

我想我并不需要它那里。没有错误,所以永远。我只是好奇我如何打开多个文件/在一个变量中读取它们。 – Ryan

+0

所以,我知道我不能这样做,但我会是这样的: $ multiplefiles = fopen(“textfile1.txt”,“textfile2.txt”,“textfile3.txt”,“r”); 现在显然你不能这样做,由于fopen参数,但有没有其他的方法来做到这一点? – Ryan

回答

0

防御性地编程,检查函数的返回值,以确保不会对代码做出不正确的假设。

PHP中的函数来读取文件和缓存它:

enter link description here

0

我不知道你为什么会想开了很多文件,它肯定会使用大量的记忆,无论如何,你可以使用file_get_contents功能与foreach

$files = array("textfile1.txt", "textfile2.txt", "textfile3.txt"); 

$data = ""; 
foreach ($files as $file) { 
    $data .= @file_get_contents($file); 
} 

echo $data; 
+0

没有想到它在一个数组中。谢谢你的提示! – Ryan

0

有一个函数在PHP称为file读取整个文件到一个数组。

<?php 

    // "file" function creates array with each line being 1 value to an array 

    $fileOne = file('fileOne.txt'); 
    $fileTwo = file('fileTwo.txt'); 

    // Print an array or do all array magic with $fileOne and $fileTwo 
    foreach($fileOne as $fo) { 
     echo $fo; 
    } 

    foreach($fileTwo as $ft) { 
     $echo $ft; 
    } 
?> 

了解更多关于:file功能离子PHP