如何使用URL迭代目录和子目录

时间:2017-05-23 15:19:35

标签: php wordpress iteration recursiveiterator

我正在尝试遍历目录中的文件和子目录中的文件:

<?php

$dir = get_stylesheet_directory_uri() . '/js';

echo $dir;

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST );

foreach ( $iterator as $path ) {
    if ($path->isDir()) {
        print('<div> DIR : ' . $path . PHP_EOL . "</div>");
    } else {
        $path_parts = pathinfo($path);
        $file_parts = $path_parts['extension'];
        if ($file_parts == "js")
        {
            $array = explode("/opt/lampp/htdocs", $path);
            unset($array[0]);
            echo $path = implode("/", $array);
            print("<div>http://localhost$path" . PHP_EOL . "</div>");
            echo("<script src='http://localhost/$path'></script>");
        } else if ($file_parts == "css") {
            echo("<script src='http://localhost/$path'></script>");
            echo("<link rel='stylesheet' href='http://localhost/$path'>");
        }
    }
}

?>
但是,我得到了错误:

Fatal error: Uncaught UnexpectedValueException: RecursiveDirectoryIterator::__construct(http://localhost/projects/wordpress_projects/wp-content/themes/rev_cust/js): failed to open dir: not implemented in /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php:40 

echo $dir; 给出:

  

http://localhost/projects/wordpress_projects/wp-content/themes/rev_cust/js

StackTrace:

Fatal error: Uncaught UnexpectedValueException: RecursiveDirectoryIterator::__construct(http://localhost/projects/wordpress_projects/wp-content/themes/rev_cust/js): failed to open dir: not implemented in /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php:40 Stack trace: #0 /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php(40): RecursiveDirectoryIterator->__construct('http://localhos...') #1 /opt/lampp/htdocs/projects/wordpress_projects/wp-includes/template.php(684): require_once('/opt/lampp/htdo...') #2 /opt/lampp/htdocs/projects/wordpress_projects/wp-includes/template.php(643): load_template('/opt/lampp/htdo...', true) #3 /opt/lampp/htdocs/projects/wordpress_projects/wp-includes/general-template.php(45): locate_template(Array, true) #4 /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/index.php(18): get_header() #5 /opt/lampp/htdocs/pro in /opt/lampp/htdocs/projects/wordpress_projects/wp-content/themes/rev_cust/header.php on line 40

如何修复它并使其正常工作?

提前谢谢大家。

2 个答案:

答案 0 :(得分:1)

RecursiveDirectoryIterator::__construct期望路径不是uri。要解决此问题,请尝试:

$dir = get_stylesheet_directory() . '/js'; // This gives you a path instead

答案 1 :(得分:0)

您正在传递网址,而您必须传递路径。

在此处查看:http://php.net/manual/en/class.recursivedirectoryiterator.php