I have /fonts/ folder full of .js files.
I know how to read this folder and list all the files there:
$dir = "/fonts"; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { echo '<tr><td>'. $file .'</td></tr>'; } closedir($dh); } }
But I don't want to write filenames but data they store.
The pattern inside looks like this:
NameOfTheFontFile_400_font.js:
(...) "font-family":"NameOfTheFont" (...)
So how to modify my first script to open-read each file and grab the font-family name instead of file name?
Thanks a lot!
From the php manual:
$lines = file($file);
Edit: This can probably be optimized, but to get the line with the font:
foreach ($lines as $line)
{
if (strpos($line, 'font-family') !== false)
{
echo $line;
}
}
You can dig further in that line using string functions or regular expressions to get the exact font name (using for example strpos()), but how to do that depends on the general format of the file.
You could use readfile()
to echo it's output. Also note that this is not tested, but it should work:
$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);
}
}
If your .js file has extra data beside the font name, you do do something like this to find the file name:
$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);
}
}
Off-topic: Why are you storing the font's names inside .js files? It would be better to store them inside a xml file or in a DB, because that's what they are made for.
From the documentation - http://www.php.net/manual/en/function.file-get-contents.php , you can use file_get_contents to get the contents of files using the filenames you got from directory listing.
string file_get_contents ( string$filename [, bool$use_include_path = false [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )
NOTE: Others have already answered the question in detail. Edited this answer in response to sel-fish's comment to elaborate on the linked documentation.
This does the job:
$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>';
}
}
Or in a different style:
$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>';
}
}
}