我正在尝试从php中的另一个文件夹包含一个文件夹的所有文件。这是我当前的目录结构:
> folder1
main.php
> folder2
> folder3
someFile.php
someFile2.php
someFile3.json
我试着做:
include "../folder2/";
这(仅包括php文件):
foreach (glob("classes/*.php") as $filename)
{
include $filename;
}
从开始main.php
,我想folder2/
包括子文件夹在内的所有内容:folder3
以及其中的php和json文件folder2/
。我看过其他堆栈溢出问题,并且了解for循环方法,但是还没有找到一种方法来包括不同的文件类型(.php,.json等)和子目录。任何帮助表示赞赏。谢谢!
PHPinclude
不应用于其他文件类型,例如.json
。要从这些文件中提取数据,您需要使用来读取它们file_get_contents
。例如:
$data = json_decode(file_get_contents('someFile3.json'));
要以递归方式将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);
此代码是此处找到的代码的修改版本:https : //gist.github.com/pwenzel/3438784
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句