Sanjana Nair
Sanjana Nair

Reputation: 2785

list particular extensions in directory format in PHP

Hi I am trying list all the html and XML formats in a particular directory using Php.

I tried the following: I succeeded with only showing html but couldn't include XML with this.

Can some help me with this:

Here is what I have tried: How do I add .xml to the below filter.

<?php
include("lock.php");

$myDirectory = opendir(".");


while ($entryName = readdir($myDirectory))
{
   if ($entryName != "." && strtolower(substr($entryName, strrpos($entryName, '.') + 1)) == 'html')
    {
      $dirArray[] = $entryName;
    }
}


closedir($myDirectory);


$indexCount = count($dirArray);
Print ("$indexCount files<br>\n");

sort($dirArray);

print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>S.No</TH><TH>Filename</TH></TR>\n"); 

for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != ".")
{ 
        print("<TR><td>");
        print($index + 1);
        print("</td>");
        print("<TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
        print("</TR>\n");
    }
}
print("</TABLE>\n");
?>

Upvotes: 2

Views: 53

Answers (3)

user10089632
user10089632

Reputation: 5550

easy, use glob

Find pathnames matching a pattern you can treat it as an array

$dirArray = glob("*.{html,HTML,xml,XML}",GLOB_BRACE);

$indexCount = count($dirArray);
Print ("$indexCount files<br>\n");
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>S.No</TH><TH>Filename</TH></TR>\n"); 

for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != ".")
{ 
        print("<TR><td>");
        print($index + 1);
        print("</td>");
        print("<TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
        print("</TR>\n");
    }
}
print("</TABLE>\n");

This solution takes care of lowercase uppercase file extensions pattern

Upvotes: 2

Jim Wright
Jim Wright

Reputation: 6058

You can use regex to check for any characters at the end of a string.

while ($entryName = readdir($myDirectory))
{
   if (preg_match(/'^.+\.(html|xml)$/', $entryName))
    {
      $dirArray[] = $entryName;
    }
}

A cleaner solution would be to use pathinfo().

while ($entryName = readdir($myDirectory))
{
    $fileParts = fileinfo($entryName);
    if(in_array($fileParts['extension'], ['html', 'xml']))
    {
        $dirArray[] = $entryName;
    }
}

Upvotes: 1

andreybleme
andreybleme

Reputation: 689

You can use glob

$count = 0;

foreach (glob("*.xml") as $file) {
    echo $file;  //the file name
    $count++;
}

echo $count;

By doing so, you can just replace the .xml to .pdf or any file extensions you're looking for. The $count variable will store the amount of files with the specified extension.

Upvotes: 1

Related Questions