Home > Backend Development > PHP Tutorial > How to List Specific Files in a PHP Directory Using glob()?

How to List Specific Files in a PHP Directory Using glob()?

Mary-Kate Olsen
Release: 2024-11-10 21:31:03
Original
495 people have browsed it

How to List Specific Files in a PHP Directory Using glob()?

Listing Specific Files in a PHP Directory

In a previous article, we explored how to list all files in a directory using PHP. While this code is straightforward, it may not always be suitable when you need to filter and display specific files.

Listing Files with a Specific Extension

To list only files with a particular file extension (such as ".xml"), we can utilize PHP's glob() function. This function takes a pattern as an argument and returns an array of filenames that match the specified pattern.

Usage

The following code snippet demonstrates how to list XML files in a directory:

$files = glob('/path/to/dir/*.xml');
foreach ($files as $file) {
    echo $file . PHP_EOL;
}
Copy after login

In this code:

  • glob() scans the specified directory and returns an array of filenames matching the pattern "*.xml".
  • We iterate over the returned array using a foreach loop and print each filename.

Additional Notes

  • The pattern used in glob() can include wildcards (? and *) to match multiple characters.
  • The pattern can also be used to specify full paths using forward slashes (/) as directory separators.
  • This method is more efficient than filtering the list of all files after retrieval, as it only retrieves matching files from the file system.

The above is the detailed content of How to List Specific Files in a PHP Directory Using glob()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template