[英]PHP How can I iterate over a directory and merge all files that end with same string in a single file of that name
描述:
我有一個包含大量文件的目錄,如下所示:
2013_11_weekly.csv
2013_10_weekly.csv
2013_08_weekly.csv
2013_09_weekly.csv
2013_11_any_string.csv
2013_10_any_string.csv
問題:
如何遍歷目錄並將所有以相同字符串結尾的文件合並為單個文件?
最終結果將是一個包含以下文件的目錄。
weekly.csv
any_string.csv
...
研究:
我有合並所有所有文件的以下代碼段。
<?php
$files = glob("*.csv");
$out = fopen("merged_files.csv", "w");
foreach($files as $file){
fwrite($out, file_get_contents($file));
}
fclose($out);
echo "files merged";
?>
如何修改腳本以實現上述目標?
我知道我可能必須使用數組函數, str_
函數以及正則表達式函數。
嘗試此操作-它假定了將文件分組的規則(2013_ [兩位數字] _ [grouping_string])。 一個不錯的技巧是在正則表達式中使用?P登錄,它將把聚合字符串放入'string_aggr'鍵下的$ maches數組中:
$filenameRegexp = '/2013_[0-9]{2}_(?P<string_aggr>.+)\.csv/';
foreach (glob('*.csv') as $filename) {
if (preg_match($filenameRegexp, $filename, $matches)) {
$aggrFilename = $matches['string_aggr'] '.csv';
file_put_contents($aggrFilename, file_get_contents(filename), FILE_APPEND);
}
}
它的作用基本上是:
運行它之后,您應該會得到理想的結果-根據您的情況,根據“所有”部分,多個文件的內容匯總:每周,any_string等。
這非常簡單,您只需要弄清楚如何從文件名中獲取公用名即可。
在我的示例中,我在第8個位置分割了文件名( 2013_11_weekly.csv
變為weekly.csv
):
$files = glob("*.csv");
$out = array();
foreach($files as $file) {
$name = substr(basename($file), 8);
if (!isset($out[$name])) {
$out[$name] = fopen($name, "w");
}
fwrite($out[$name], file_get_contents($file));
}
foreach ($out as $f) {
fclose($f);
}
這可能對您有幫助。 如果您沒有得到正確的答案,請告訴我。 使用php合並多個csv文件
您可以創建一個數組,將所有值連接到數組中,然后創建這些文件
例如 :
$files = glob("*.csv");
$files_content = array();
//parse all your files
foreach($files as $file){
//get the suffix (ie '_weekly')
$filename_end = substr(basename($file), 8);
if(!isset($files_content[$file])) $files_content[$file] = "";
//concatenate strings
$files_content[$file] .= file_get_contents($file);
}
//and then create those files
foreach($fields_content as $filename => $content){
$out = fopen($filename, "w");
fwrite($out, $content);
fclose($out);
}
而不是fwrite,應該使用file_put_content 。 此功能能夠將數據追加到文件中。
描述
int file_put_contents(字符串$ filename,混合$ data [,int $ flags = 0 [,resource $ context]])
此函數與依次調用fopen(),fwrite()和fclose()來將數據寫入文件相同。
如果文件名不存在,則創建文件。 否則,除非設置了FILE_APPEND標志,否則現有文件將被覆蓋。
產生如下代碼(未經測試,僅用於理解):
<?php
$files = glob("*.csv");
foreach($files as $file){
// get substring 6 chars before the last 4 chars (.csv)
$type = substr($file, -4, -10)
// switch based on the substring $type
switch($type) {
case "weekly":
file_put_content("merged_files_weekly.csv", file_get_contents($file), FILE_APPEND);
break;
case "string" :
file_put_content("merged_any_string.csv", file_get_contents($file), FILE_APPEND);
break;
default:
// do nothing
break;
}
}
echo "files merged";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.