John Down
John Down

Reputation: 520

Read Multiple Text Files based on dated name and write all to concatenate string

I am very new to PHP and stared learning this week and I'm stuck at this problem.

I have multiple text files with names based on dates. I need to read every file within a date range and concatenate the text together into one long string.

What I have so far:

Creates different dates as strings and writes to variable $datef:

while (strtotime($date) <= strtotime($end_date)) {
$datef="$date\n";
$date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
}

Variable $datef is used in dynamic file name:

$file = file_get_contents('idfilebuy'.$datef.'.txt');
$string = ???? (all files to variable $string as concatenate string??)

Any ideas would be greatly appreciated.

Upvotes: 2

Views: 149

Answers (1)

BentoumiTech
BentoumiTech

Reputation: 1683

Your code as you mentionned overwrite the content of $date variable at each iterations so when you run $file = file_get_contents('idfilebuy'.$datef.'.txt'); $datedef on contain the last while iterations.

You need to retreive each file inside your while statement.

$string = '';
while (strtotime($date) <= strtotime($end_date)) {
    $datef="$date";
    $fileContent = file_get_contents('idfilebuy'.$datef.'.txt');
    $string .= $fileContent;
    $date = date ("Y-m-d", strtotime("+1 day", strtotime($date)));
}
var_dump($string);

Upvotes: 2

Related Questions