2012-01-10 52 views
1

我想從我的目錄/ img中簡單地拉出圖像,並將它們動態加載到網站中,以下列方式。從目錄拉圖片 - PHP

  <img src="plates/photo1.jpg"> 

就是這樣。看起來很簡單,但我找到的所有代碼基本上都不起作用。

我有什麼,我努力使工作是這樣的:

<?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."' />"; 
} 
?> 
+3

定義「不起作用」。有錯誤嗎?代碼返回什麼_does_?如果你調試它,觀察到的行爲在什麼時候會偏離預期的行爲?什麼時候發生相關的運行時間值? – David 2012-01-10 16:06:50

+0

「不起作用」太模糊。你有錯誤嗎?如果是,請描述它?否則會發生什麼,你不指望? – 2012-01-10 16:07:48

+0

僅僅匹配文件擴展名的正則表達式效率非常低。但是,如果你堅持,你至少應該結合三種文件類型。 – kba 2012-01-10 16:11:15

回答

3

您希望您的源顯示爲plates/photo1.jpg,但是當你做echo "<img src='".$i."' />";你只寫文件名。嘗試將其更改爲這樣:

<?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 . "' />"; 
} 
?> 
1

您應該使用Glob,而不是執行opendir/closedir的。它更簡單。

我不能完全確定你想要做什麼,而是你這個可能讓你在正確的軌道

<?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 
    } 
} 
?> 
+0

glob更好,但DirectoryIterator再次更好 – robjmills 2012-01-10 16:20:42

+0

直到現在我還沒有聽說過。看起來不錯。 – Catfish 2012-01-10 16:32:32

4

這可以很容易使用​​3210上做。

$files = glob("plates/*.{png,jpg,jpeg}", GLOB_BRACE); 
foreach ($files as $file) 
    print "<img src=\"plates/$file\" />"; 
+0

工作正常,只需更換打印線即可: 'echo' Xavier 2012-08-30 10:12:55