在我的web应用程序中,我想在php中列出一个目录“file /*-pairings.txt”的内容,因此我有一个php文件(下面),它应该将这些内容读入数组,并编写包含json的文件“file /contents.json”。
contents.json应该如下所示:
"2012-01-02-pairings.txt“、"2012-05-17-pairings.txt”、"2021-03-17-pairings.txt“
我尝试了下面的代码(从网络),但"contents.json“只是空白。
我该怎么做?
<?php
$arrFiles = array();
$iterator = new FilesystemIterator("archives");
foreach($iterator as $entry) {
$arrFiles[] = $entry->getFilename();
}
$myfile = fopen("archives/contents.json", "w");
fwrite ($myfile, $arrFiles);
fclose ($myfile);
?>同样的结果也适用于以下代码:
<?php
$arrFiles = array();
$objDir = dir("archives");
while (false !== ($entry = $objDir->read())) {
$arrFiles[] = $entry;
}
$objDir->close();
$myfile = fopen("archives/contents.json", "w");
fwrite ($myfile, $arrFiles);
fclose ($myfile);
?>发布于 2022-05-07 08:09:05
function list_contents($dir) {
$contents = array();
$dir = realpath($dir);
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..' && $file != 'contents.json') {
$contents[] = $file;
}
}
}
$contents_json = json_encode($contents);
file_put_contents($dir . '/contents.json', $contents_json);
}对于我来说,这是一个简单的函数,它读取目录中的文件并将其放入contents.json。
如果您希望它有一个特定的后缀,那么很容易更改为此:
function list_contents($dir, $suffix) {
$contents = array();
$dir = realpath($dir);
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..' && $file != 'contents.json') {
if (substr($file, -strlen($suffix)) == $suffix) {
$contents[] = $file;
}
}
}
}
$contents_json = json_encode($contents);
file_put_contents($dir . '/contents.json', $contents_json);
}https://stackoverflow.com/questions/72150379
复制相似问题