2011-07-08 28 views
4

我有一個腳本,通過具有3個圖像PHP使用目錄中的文件

$imglist=''; 
$img_folder = "path to my image"; 

//use the directory class 
$imgs = dir($img_folder); 

//read all files from the directory, checks if are images and ads them to a list 
while ($file = $imgs->read()) { 
    if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file)) 
    $imglist .= "$file "; 
} 
closedir($imgs->handle); 

//put all images into an array 
$imglist = explode(" ", $imglist); 

//display image 
foreach($imglist as $image) { 
    echo '<img src="'.$img_folder.$image.'">'; 
} 

但我有是顯示第四IMG無圖像的問題目錄不用..但我只有3該文件夾中的圖像。

+0

測試你的代碼文件名爲「this_is_text_not_png.txt」 – horatio

回答

6

沒有必要構建一串圖像,然後將該字符串分解爲一組圖像,而不是像Radu所提到的那樣直接將圖像添加到數組中。 以下是更正代碼:

$imglist = array(); 
$img_folder = "path to my image"; 

//use the directory class 
$imgs = dir($img_folder); 

//read all files from the directory, checks if are images and adds them to a list 
while ($file = $imgs->read()) { 
    if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file)){ 
     $imglist[] = $file; 
    } 
} 
closedir($imgs->handle); 

//display image 
foreach($imglist as $image) { 
    echo '<img src="'.$img_folder.$image.'">'; 
} 
+0

謝謝。我嘗試通過將shuffle()隨機加載列表,但我沒有運氣我正在嘗試學習PHP,所以我非常感謝它。 –

+0

得到它的工作非常感謝 –

+0

如果你有一個錯誤Directory :: read()方法未找到 - 請嘗試pth_read()而不是read() - 無證「功能」 –

2

您將在$imglist字符串末尾留出空格,explode()將變成空白元素。修剪字符串:

$imglist = explode(" ", trim($imglist)); 

或者更好的是,只需將它們添加到$imglist陣列擺在首位,而不是使一個字符串,它爆炸:

$imglist = array(); 
/* ... */ 
$imglist[] = $file; 
+0

感謝怎麼樣使它隨機的? –

+0

你可以使用['shuffle()'](http://php.net/shuffle)來隨機化數組的內容。 – rid

+0

得到它的工作非常感謝 –

2

額日格()已過時。你可能會與更好:

chdir($img_folder); 
$imgs = glob('*.jpg *.gif *.png'); 
foreach ($imgs as $img) { 
    echo "<img src=\"{$img_folder}/{$img}\">"; 
} 

glob()確實通配符匹配幾乎相同的方式,大多數的Unix炮彈做。

+0

此外,eregi被用來匹配文件名上的任何位置的子字符串。 –

0
Use [glob()][1] function 
<?php 
    define('IMAGEPATH', 'path to my image/'.$imglist.'/'); 
    foreach(glob(IMAGEPATH.'*.jpg') as $filename){ 
     echo '<img src="'.$filename.'" alt="'.$album.'" />'; 

    ?> 

    [1]: http://www.php.net/manual/en/function.glob.php