[英]Include all files in a folder - PHP
I'm trying to include all files from a folder from another folder in php.我正在尝试包含 php 中另一个文件夹的文件夹中的所有文件。 Here is my current directory structure:
这是我当前的目录结构:
> folder1
main.php
> folder2
> folder3
someFile.php
someFile2.php
someFile3.json
I tried doing:我试着做:
include "../folder2/";
and this(only includes php files):和这个(仅包括 php 文件):
foreach (glob("classes/*.php") as $filename)
{
include $filename;
}
From main.php
, I want to include all of folder2/
including the sub folder: folder3
as well as the php and json files inside folder2/
.从
main.php
,我想包括所有的folder2/
包括子文件夹: folder3
以及 php 和 json 文件里面的folder2/
。 I have looked at other stack overflow questions and know about the for loop method but haven't figured out a way to include different file types(.php, .json, etc...) and sub directories.我查看了其他堆栈溢出问题并了解 for 循环方法,但还没有找到包含不同文件类型(.php、.json 等)和子目录的方法。 Any help is appreciated.
任何帮助表示赞赏。 Thanks!
谢谢!
PHP's include
shouldn't be used for other file types, like .json
. PHP 的
include
不应用于其他文件类型,例如.json
。 To extract data from those files you'll want to read them using something like file_get_contents
.要从这些文件中提取数据,您需要使用类似
file_get_contents
的方式读取它们。 For example:例如:
$data = json_decode(file_get_contents('someFile3.json'));
To recursively include the PHP files in other directories you can try recursively searching through all directories:要递归地将 PHP 文件包含在其他目录中,您可以尝试递归搜索所有目录:
function require_all($dir, $max_scan_depth, $depth=0) {
if ($depth > $max_scan_depth) {
return;
}
// require all php files
$scan = glob("$dir/*");
foreach ($scan as $path) {
if (preg_match('/\.php$/', $path)) {
require_once $path;
}
elseif (is_dir($path)) {
require_all($path, $max_scan_depth, $depth+1);
}
}
}
$max_depth = 255;
require_all('folder3', $max_depth);
This code is a modified version of the code found here: https://gist.github.com/pwenzel/3438784此代码是此处代码的修改版本: https://gist.github.com/pwenzel/3438784
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.