Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP string append is overwriting instead when loading in content from files within a loop?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading