在我的網路應用程式中,我想在 php 中列出目錄“archives/*-pairings.txt”的內容所以我有一個 php 檔案(如下)應該將這些內容讀入陣列并寫入檔案“archives/ contents.json" 包含 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);
?>
uj5u.com熱心網友回復:
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://www.uj5u.com/houduan/470170.html
