2014-02-17 41 views
2

我試圖建立一個小畫廊基於david walsh's howto.圖片ALT標籤在文本文件中檢索由PHP

現在,這個畫廊提供了使用圖片的文件名ALT標籤。我需要一種方法來使用一個文本文件,用我的圖像相關聯的,是這樣的:

myprettypicture.jpg = "Here's a pretty picture" 
mynotsoprettypicture.jpg = "Here's a not so pretty picture" 

然後檢索該把儘可能ALT變量與PHP庫。到目前爲止,我已經看過幾個畫廊,還有一些使用這種方法,但我不知道如何使用它與我的實際畫廊...
你知道一個腳本或一個簡單的方法接近我正在尋找?

謝謝!

回答

1

如果我正確理解你,你有一個source_file.htm,如下所示。現在

<!DOCTYPE html> 
<html> 
<body> 
<img src="myprettypicture.jpg" alt="myprettypicture.jpg" height="50" width="50"> 
<img src="mynotsoprettypicture.jpg" alt="mynotsoprettypicture.jpg" height="50" width="50"> 
</body> 
</html> 

,這是更好地爲您的圖片的alt標籤的替代存儲在一個文件images.ini那樣。

myprettypicture.jpg = "Here's a pretty picture" 
mynotsoprettypicture.jpg = "Here's a not so pretty picture" 

現在你可以運行這個PHP腳本:

<?php 
$ini_array = parse_ini_file("images.ini"); // load "images.ini" into array 
foreach($ini_array as $key => $val) 
{ 
    $img[] = 'alt="' . $key . '"'; 
    $alt[] = 'alt="' . $val . '"'; 
} 
$source = file_get_contents('source_file.htm'); // get Your "source_file.htm" 
$target = str_replace($img, $alt, $source);  // make all required replacements 
file_put_contents('target_file.htm', $target); // save the result to "target_file.htm" 
?> 

得到target_file.htm

<!DOCTYPE html> 
<html> 
<body> 
<img src="myprettypicture.jpg" alt="Here's a pretty picture" height="50" width="50"> 
<img src="mynotsoprettypicture.jpg" alt="Here's a not so pretty picture" height="50" width="50"> 
</body> 
</html> 

參考: str_replaceparse_ini_filefile_get_contentsfile_put_contents

+0

這正是我被搜索興奮:某種圖像文件夾的.ini包裝。非常感謝您的評論,非常有用。 – mediaklan