PHP 获取内容图像文件夹 SVG



我正在尝试从文件夹中获取svg文件。

尝试了以下方法,但似乎都不起作用:

<?php   
$directory = get_bloginfo('template_directory').'/images/myImages/';      
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while ($it->valid()) { //Check the file exist
if (!$it->isDot()) { //if not parent ".." or current "."
if (strpos($it->key(), '.php') !== false
|| strpos($it->key(), '.css') !== false
|| strpos($it->key(), '.js') !== false
) {
echo $it->key() . '<br>';
}
}
}
?>

和:

global $wp_filesystem;
$path = get_bloginfo('template_directory').'/images/myImages/';
$filelist = $wp_filesystem->dirlist( $path );
echo $filelist;

和:

$path = get_bloginfo('template_directory').'/images/myImages/';
$images = scandir( $path, 'svg', $depth = 0);
echo $images;

和:

$dir    = get_bloginfo('template_directory').'/images/myImages/';
$files = scandir($dir);
print_r($files);

和:

$directory = get_bloginfo('template_directory')."/images/myImages/";
$images = glob($directory . "*.svg");
echo '<pre>';
print_r($images);
echo '</pre>';
echo $directory.'abnamro.svg">';
foreach($images as $image)
{
echo $image;
}

我有点迷茫。我可能会认为还有其他问题。
还检查了用户的权限,但一切都很好。 我在带有 MAMP 的本地机器上运行 Wordpress。

有什么想法吗?

尝试下面的功能,为了清楚起见,我已经注明了。一些亮点是:

  1. 您可以在目录迭代器中跳过开头的点
  2. 如果路径不存在,您可能会触发致命错误(在这种情况下,这是问题所在,您使用的是域根路径而不是服务器根路径 [ABSPATH](
  3. 您可以选择扩展名类型来过滤文件

function getPathsByKind($path,$ext,$err_type = false)
{
# Assign the error type, default is fatal error
if($err_type === false)
$err_type   =   E_USER_ERROR;
# Check if the path is valid
if(!is_dir($path)) {
# Throw fatal error if folder doesn't exist
trigger_error('Folder does not exist. No file paths can be returned.',$err_type);
# Return false incase user error is just notice...
return false;
}
# Set a storage array
$file   =   array();
# Get path list of files
$it     =   new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::SKIP_DOTS)
);
# Loop and assign paths
foreach($it as $filename => $val) {
if(strtolower(pathinfo($filename,PATHINFO_EXTENSION)) == strtolower($ext)) {
$file[] =   $filename;
}
}
# Return the path list
return $file;
}

要使用:

# Assign directory path
$directory = str_replace('//','/',ABSPATH.'/'.get_bloginfo('template_directory').'/images/myImages/');
# Get files
$files = getPathsByKind($directory,'svg');
# Check there are files
if(!empty($files)) {
print_r($files);
}

如果路径不存在,它现在将通过系统错误告诉您该路径不存在。如果它没有抛出致命错误并且出现空,那么您实际上确实遇到了一些奇怪的问题。

如果一切顺利,你应该得到这样的东西:

Array
(
[0] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img1.svg
[1] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img2.svg
[2] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img3.svg
[3] => /data/19/2/133/150/3412/user/12321/htdocs/domain/images/myImages/img4.svg
)

如果路径无效,将抛出:

致命错误:文件夹不存在。不能返回任何文件路径。在/data/19/2/133/150/3412/user/12321/htdocs/domain/index.php123

最新更新