从目录中拉出图像 - PHP
I am trying to pull images simply from my directory /img and load them dynamically into the website into the following fashion.
<img src="plates/photo1.jpg">
That's it. It seems so simple but all of the code I have found basically doesn't work.
What I have that I am trying to make work is this:
<?php
$a=array();
if ($handle = opendir('plates')) {
while (false !== ($file = readdir($handle))) {
if(preg_match("/\.png$/", $file))
$a[]=$file;
else if(preg_match("/\.jpg$/", $file))
$a[]=$file;
else if(preg_match("/\.jpeg$/", $file))
$a[]=$file;
}
closedir($handle);
}
foreach($a as $i){
echo "<img src='".$i."' />";
}
?>
我正在尝试从我的目录/ img中提取图像,并将它们动态加载到网站中,形式如下。 p>
&lt; img src =“plates / photo1.jpg”&gt;
code> pre>
就是这样。 它似乎很简单,但我发现的所有代码基本上都不起作用。 p>
我想要做的工作是: p>
&lt;?php
$ a = array();
if($ handle = opendir('plates')){
while(false!==($ file = readdir($ handle) )){
if(preg_match(“/ \。png $ /”,$ file))
$ a [] = $ file;
else if(preg_match(“/ \。jpg $ /”,$ file) )
$ a [] = $ file;
else if(preg_match(“/ \ .jpeg $ /”,$ file))
$ a [] = $ file;
}
nclosedir($ handle );
}
foreach($ a as $ i){
echo“&lt; img src ='”。$ i。“'/&gt;”;
}
?&gt;
pre>
div>
You want your source to show up as plates/photo1.jpg
, but when you do echo "<img src='".$i."' />";
you are only writing the file name. Try changing it to this:
<?php
$a = array();
$dir = 'plates';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
foreach ($a as $i) {
echo "<img src='" . $dir . '/' . $i . "' />";
}
?>
You should use Glob instead of opendir/closedir. It's much simpler.
I'm not exactly sure what you're trying to do, but you this might get you on the right track
<?php
foreach (glob("/plates/*") as $filename) {
$path_parts = pathinfo($filename);
if($path_parts['extension'] == "png") {
// do something
} elseif($path_parts['extension'] == "jpg") {
// do something else
}
}
?>
This can be done very easily using glob()
.
$files = glob("plates/*.{png,jpg,jpeg}", GLOB_BRACE);
foreach ($files as $file)
print "<img src=\"plates/$file\" />";