Home > Back-end >  PHP string append is overwriting instead when loading in content from files within a loop?
PHP string append is overwriting instead when loading in content from files within a loop?

Time:10-09

I am attempting to read in multiple files, where the filename of each file is contained within a central file "order.txt", and take the content and append it to a single string variable in PHP.

This is my current approach:

$order = file("order.txt");
$content = "";
foreach($order as $line) {
    $content = $content . file_get_contents($line);
}
return $content;

order.txt

one.txt
two.txt
three.txt

However, when "content" is returned, it only contains the data within the last file (in this case, "three.txt"). How can I ensure the content from all files are appended to the "content" variable?

CodePudding user response:

I haven't tried your code, but PHP's file returns lines with line breaks (\n). So instead of reading one.txt, you are trying to read from a file one.txt\n.

The reason why you actually get the contents of three.txt, is that the last line presumably has no newline character in the end (actually it's not called a line). Always add newlines; if the file is written automatically, make sure to add \n after each line.

You can add FILE_IGNORE_NEW_LINES as second parameter to file().

Btw: Your PHP doesn't seem to be configured correctly as you don't see any warnings about that one.txt\n doesn't exist. You should turn on all error messages, set display_errors to true or at least monitor PHP's error log.

  • Related