我需要獲取目錄中的幾個文件的內容,但這是做到這一點的最佳方式?檢索目錄中的幾個文件的內容PHP
我使用
$data = file_get_contents('./files/myfile.txt');
,但我想,而無需指定該文件作爲各自如上每個文件。
我需要獲取目錄中的幾個文件的內容,但這是做到這一點的最佳方式?檢索目錄中的幾個文件的內容PHP
我使用
$data = file_get_contents('./files/myfile.txt');
,但我想,而無需指定該文件作爲各自如上每個文件。
您可以使用glob
獲得特定的文件擴展和file_get_contents
獲取內容
$content = implode(array_map(function ($v) {
return file_get_contents($v);
}, glob(__DIR__ . "/files/*.txt")));
/**
* Change the path to your folder.
* This must be the full path from the root of your
* web space. If you're not sure what it is, ask your host.
*
* Name this file index.php and place in the directory.
*/
// Define the full path to your folder from root
$path = "/home/content/s/h/a/shaileshr21/html/download";
// Open the folder
$dir_handle = @opendir($path) or die("Unable to open $path");
// Loop through the files
while ($file = readdir($dir_handle)) {
$data = file_get_contents('$filet');
}
// Close
closedir($dir_handle);
您可以通過目錄查看目錄並循環查看所有文件的內容。
if (!($entry == '..' || $entry == '.')) {
到:
<?php
$path = './files';
$d = dir($path);
$contents = '';
while (false !== ($entry = $d->read())) {
if (!($entry == '..' || $entry == '.')) {
$contents .= file_get_contents($path.'/'.$entry);
}
}
$d->close();
?>
如果你只是想.txt文件,你可以從上面的改變代碼的if語句
if (substr($entry, -4) == '.txt') {
這將導致一個變量$內容即字符串類型,幷包含所有文件中的所有內容(如果選擇第二種解決方案,則只包含txt文件),該文件位於./files目錄中。
使用循環,但你爲什麼不細說嗎? – str 2013-04-24 12:15:47
'opendir'和'readdir'除了循環? http://php.net/manual/en/function.readdir.php – AlexP 2013-04-24 12:19:38