2011-01-20 85 views
0

我有/字體/文件夾完整的.js文件。PHP - 讀取文件和回顯結果

我知道如何閱讀這個文件夾並列出存在的所有文件:

$dir = "/fonts"; 
     if (is_dir($dir)) {  
      if ($dh = opendir($dir)) { 
       while (($file = readdir($dh)) !== false) { 
        echo '<tr><td>'. $file .'</td></tr>'; 
       } 
      closedir($dh); 
      } 
     } 

但我不想寫的文件名,但他們存儲數據。

模式裏面看起來是這樣的:

NameOfTheFontFile_400_font.js:

(......) 「FONT-FAMILY」: 「NameOfTheFont」(...)

那麼如何修改我的第一個腳本來打開讀取每個文件並獲取字體系列名稱而不是文件名?

非常感謝!

回答

0

php manual

$lines = file($file); 

編輯:這可能可以優化,但得到的字體行:

foreach ($lines as $line) 
{ 
    if (strpos($line, 'font-family') !== false) 
    { 
    echo $line; 
    } 
} 

您可以在使用線串進一步挖掘函數或正則表達式來獲取確切的字體名稱(例如使用strpos()),但如何做到這一點取決於文件的一般格式。

+0

我知道如何打開一個文件,但我不知道如何抓住確切的詞。 – anonymous 2011-01-20 13:30:17

+0

@anonymous我已經添加了一些更多的細節來獲得正確的路線。 – jeroen 2011-01-20 13:58:55

0

您可以使用readfile()來回顯它的輸出。另外請注意,這不是測試,但它應該工作:

$dir = "/fonts"; 
    if (is_dir($dir)) {  
     if ($dh = opendir($dir)) { 
      while (($file = readdir($dh)) !== false) { 
       echo '<tr><td>'; 
       readfile($file); 
       echo '</td></tr>'; 
      } 
     closedir($dh); 
     } 
    } 

如果你的.js文件具有字體名稱旁邊額外的數據,你做這樣的事情要查找的文件名:

$dir = "/fonts"; 
    if (is_dir($dir)) {  
     if ($dh = opendir($dir)) { 
      while (($file = readdir($dh)) !== false) { 
       $lines = file($file); 
       foreach ($lines as $line) { 
        if (preg_match('/("font-family":)(".+")/', $line, $parts)) {     
         echo '<tr><td>', $parts[2], '</td></tr>'; 
        } 
       } 
      } 
     closedir($dh); 
     } 
    } 

偏題:你爲什麼要在.js文件中存儲字體的名字?將它們存儲在xml文件或DB中會更好,因爲這就是它們的作用。

0

從文檔 - http://www.php.net/manual/en/function.file-get-contents.php,您可以使用file_get_contents從目錄列表中獲取文件的內容。

string file_get_contents ( string$filename [, bool$use_include_path = false [, resource $context [, int $offset = 0 [, int $maxlen ]]]])

注:其他人已經回答了具體的問題。編輯這個答案是爲了迴應sel-fish的意見,詳細說明鏈接的文檔。

0

這做工作:

$dir = '/fonts'; 

$files = array_filter(glob("$dir/*"), 'is_file'); 
$contents = array_map('file_get_contents', $files); 
foreach ($contents as $content) { 
     if (preg_match('#"font-family":"([^"]+)"#', $content, $matches)) { 
       echo '<tr><td>'.htmlspecialchars($matches[1]).'</td></tr>'; 
     } 
} 

或以不同的風格:

$files = glob("$dir/*"); 
foreach($files as $file) { 
     if (is_file($file)) { 
       $content = file_get_contents($file); 
       if (preg_match('#"font-family":"([^"]+)"#', $content, $matches)) { 
         echo '<tr><td>'.htmlspecialchars($matches[1]).'</td></tr>'; 
       } 
     } 
}