Home > Net >  php list files to array and save array stringified to disk
php list files to array and save array stringified to disk

Time:05-07

In my web app I want to list in php the contents of a directory "archives/*-pairings.txt" So I have a php file (below) that is supposed to read those contents into an array and write the file "archives/contents.json" containing json.

contents.json should look like this:

["2012-01-02-pairings.txt","2012-05-17-pairings.txt","2021-03-17-pairings.txt"]

I tried the code below (from the web) but "contents.json" was just blank.

How can I do this?

<?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);
?>

The same result was with the code below:

<?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);
?>

CodePudding user response:

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);
}

This works for me a simple function that reads the files at the directory and puts it into contents.json.

Easily changed to this if you want it to have a specific suffix:

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);
}
  • Related