php 列出文件到数组并将数组字符串化保存到磁盘

php list files to array and save array stringified to disk

在我的网络应用程序中,我想在 php 中列出目录“archives/*-pairings.txt”的内容 所以我有一个 php 文件(如下),它应该将这些内容读入一个数组并写入包含 json.[=13 的文件“archives/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);
?>
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);
}