我有一个文件数组,每个文件都有完整的目录路径。我需要迭代我的文件数组,然后删除其中任何 0 字节/非内容的文件。
文件.txt
/lib/Zend/Gdata/App/LoggingHttpClientAdapterSocket.php
/lib/Zend/Gdata/App/Extension.php
/lib/Zend/Gdata/App/MediaEntry.php
/lib/Zend/Gdata/App/FeedEntryParent.php
/lib/Zend/Gdata/App/AuthException.php
/lib/Zend/ProgressBar/Adapter.php
/lib/Zend/ProgressBar/alias.php
/lib/Zend/Locale/code.php
/lib/Zend/Server/Reflection/Function/article.php
/lib/Zend/Server/Reflection/ReturnValue.php
/lib/Zend/Server/Reflection.php
/lib/Zend/Dojo/BuildLayer.php
/lib/Zend/Tag/Cloud/start.php
/lib/Zend/Tag/Cloud/user.php
/lib/Zend/Tag/Item.php
/lib/Zend/Tag/Cloud.php
/lib/Zend/Ldap/Filter/Not.php
/lib/Zend/Ldap/Filter/And.php
/lib/Zend/Ldap/Filter/Exception.php
/lib/Zend/Ldap/Node.php
/lib/Zend/Ldap/Exception.php
PHP
// list of files to download
$lines = file('files.txt');
// Loop through our array of files from the files.txt file
foreach ($lines as $line_num =>$file) {
echo htmlspecialchars($file) . "<br />\n";
// delete empty files
}
最佳答案
到目前为止,您的基本循环看起来不错,我认为接下来您会感兴趣的是 filesize()
和 unlink()
:
$lines = file('files.txt', FILE_IGNORE_NEW_LINES);
foreach ($lines as $line_num => $file) {
$file_label = htmlspecialchars($file);
echo $file_label . "<br />\n";
if (!file_exists($file)) {
echo "file " . $file_label . " does not exist<br />\n";
} else if (filesize($file) === 0) {
echo "deleting file: " . $file_label . "<br />\n";
unlink($file);
}
}
虽然你应该非常小心,以确保它只删除特定目录中的文件,但可能有一个永远不应该删除的文件的白名单,等等。
更新 评论中的一个很好的说明是在 file()
调用中使用 FILE_IGNORE_NEW_LINES
剥离 \r
和 \n
每行返回的字符 =]
关于php - 迭代 PHP 文件数组并删除任何没有内容的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32617295/