2011-12-24 58 views
0

我有一個頁面,用下面的代碼顯示的默認圖像:如何將文件名傳遞給「img src」?

echo "<tr><td valign='top' colspan='4' align='center'> <img src='../wp-content/gallery/playerphotos/NoPhotoAvailable.png' width='180' height='180' border='1'></td></tr>"; 

我也有一個變量可用$行[「lng_RecordID_PK」]。

我想通過變量作爲文件名。

如果/ playerphoto /文件夾中有匹配的文件,則顯示該圖像。否則,顯示默認圖像「NoPhotoAvailable.png」。

感謝您的幫助。

+0

請告訴我這$的價值行['lng_RecordID_PK']變量 – 2011-12-24 01:39:27

+0

它通常是一個介於1至2000之間的數字 – DoubleA 2011-12-24 01:45:13

回答

0

首先,你需要定義圖像的位置,你正在尋找:

$fileLocation = "./playerphoto/" . $row['lng_RecordID_PK']; 

我不知道的路徑到該文件夾​​,用正確的相對路徑替換「./playerphoto/」。如果$ row ['lng_RecordID_PK']的值沒有返回文件擴展名,則需要在;之前添加. '.png'或任何擴展名到該行的末尾。

然後檢查它是否存在,如果不使用默認位置:

if (!file_exists($fileLocation)) { 
    // Change the file location if it does not exist. 
    $fileLocation = "../wp-content/gallery/playerphotos/NoPhotoAvailable.png"; 
} 

然後你就可以用正確的SRC呼應你的元素:

echo "<tr><td valign='top' colspan='4' align='center'> <img src='" . $fileLocation . "' width='180' height='180' border='1'></td></tr>"; 
+0

這是我從您的建議創建的代碼: $ playerfileLocation =」。 ./wp-content/gallery/playerphotos/ 「$行[ 'lng_RecordID_PK']」 .JPG 「; 如果(file_exists($ playerfileLocation)) 回聲」 「;否則 回波 」 「; 我的語法有什麼問題嗎?我通過的變量是「1539」。 – DoubleA 2011-12-24 02:21:58

0
if (file_exists($yourFilePath)) 
    echo "<tr><td valign='top' colspan='4' align='center'> <img src='$yourFilePath' width='180' height='180' border='1'></td></tr>"; 
else 
    echo "<tr><td valign='top' colspan='4' align='center'> <img src='../wp-content/gallery/playerphotos/NoPhotoAvailable.png' width='180' height='180' border='1'></td></tr>"; 
0

使用file_exists()

if(file_exists($row['lng_RecordID_PK'])) 
    $filename = $row['lng_RecordID_PK']; 
else 
    $filename = "NoPhotoAvailable.png"; // Adjust the path 

... 
... 
<img src="$filename" /> 
+0

我將始終有變量...但只有時纔會有圖像。我將如何格式化if語句包含路徑JPG文件: 「」 ../wp-content/gallery/playerphotos/「 – DoubleA 2011-12-24 02:27:54

0
 
//if $row['lng_RecordID_PK']. has file path as well 
if(file_exists($row['lng_RecordID_PK'])) { 
    $imageFile = $row['lng_RecordID_PK']; 
} 
else { 
    $imageFile = 'NoPhotoAvailable.png'; 
} 
echo "<tr><td valign='top' colspan='4' align='center'> <img src='".$imageFile."' width='180' height='180' border='1'></td></tr>"; 

相關問題