简体   繁体   English

PHP流上下文 - >在这种情况下如何使用?

[英]PHP stream context -> how to use in this scenario?

I have a system that stores user comments in its own individual json file. 我有一个系统将用户注释存储在自己的json文件中。 I use scandir(); 我用scandir(); on the directory which gets all files and folders, but how do I limit it to json files, I don't want other files such as "." 在获取所有文件和文件夹的目录上,但如何将其限制为json文件,我不想要其他文件,如“。” and ".." in the array because I need an accurate count. 和数组中的“..”,因为我需要一个准确的计数。

I checked out the info on php.net but couldn't figure it out, perhaps you know of a resource you can point me toward, or which function to use. 我检查了php.net上的信息,但无法弄明白,也许你知道你可以指向我的资源,或者使用哪个功能。

This is a lovely example where the PHP library comes to the rescue. 这是PHP库拯救的一个可爱的例子。 FilterIterator is a class that you extend and override its accept method to use only the files you want. FilterIterator是一个扩展和覆盖其accept方法的类,只使用您想要的文件。 In this case we use a standard FilesystemIterator to iterate over a directory. 在这种情况下,我们使用标准的FilesystemIterator迭代目录。 You could also use a RecursiveDirectoryIterator if you want to search for json files in sub-directories. 如果要在子目录中搜索json文件,也可以使用RecursiveDirectoryIterator This example iterates over json files in the current directory: 此示例迭代当前目录中的json文件:

class StorageFilterIterator extends FilterIterator {

    function accept() {
        $item = $this->getInnerIterator()->current();
        return $item->isFile() && $item->getExtension() === 'json';
    }

}

$storageFiles = new StorageFilterIterator(new FilesystemIterator(__DIR__));

foreach ($storageFiles as $item) {
    echo $item;
}

getExtension exists in PHP >= 5.3.6 getExtension存在于PHP> = 5.3.6中


Another lesser-known part of the Standard PHP Library (SPL) is iterator_to_array . 标准PHP库(SPL)的另一个鲜为人知的部分是iterator_to_array So if you want all of the items in an array instead of just iterating over them, you can do the following: 因此,如果您想要数组中的所有项而不是迭代它们,您可以执行以下操作:

$storageFiles = iterator_to_array(
    new StorageFilterIterator(new FilesystemIterator(__DIR__))
);

There are no stream context parameters that will help you filter out the types of files. 没有流上下文参数可以帮助您过滤掉文件类型。

Assuming that your JSON files are saved with the .json extension, you just have to filter out the array based on the file extensions. 假设您的JSON文件以.json扩展名保存,您只需根据文件扩展名过滤掉该数组。

You can use readdir() to build a list of files, or simply loop over the results you get from scandir and create a new array from that. 您可以使用readdir()来构建文件列表,或者只是循环遍历从scandir获得的结果并从中创建一个新数组。

Here is an example using readdir : 以下是使用readdir的示例:

$files = array();
$dh = opendir($path);
while (($file = readdir($dh) !== false) {
    if (pathinfo($path . '/' . $file, PATHINFO_EXTENSION) !== 'json') continue;
    $files[] = $path . '/' . $file;
}

closedir($dh);

// $files now has an array of json files

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM