I'm reading a file in PHP line by line by using a custom line delimeter, but i'm having difficulty concatenating the line character back onto the string after.
$newhtml = "";
if ($handle) {
while (($line = stream_get_line($handle, 4096, "</br>")) !== false)
{
$newhtml = "{$line}{$newhtml}" . "</br>";
}
echo $newhtml;
fclose($handle);
I'd be expecting each line of the file to come out on different lines, but the tag isn't even being shown in the dev console.
Actually with your existing block of code below
while (($line = stream_get_line($handle, 4096, "</br>")) !== false) {
$newhtml = "{$line}{$newhtml}" . "</br>"; // problem happening here with =
}
You're overwriting the $newhtml
value with every while loop iteration.So, you'll get only the last value after the iteration ends. As I understand your requirement, you want to concatenate every line to the $newhtml
variable. To do so just modify this like
$newhtml = "{$line}{$newhtml}" . "</br>";
to
$newhtml.= $line."</br>"; // with dot before =
Look an extra dot(.
) before the equal sign and remove the unnecessary usage of {$newhtml} variable again
From the code you given I can guess that you want to put last line as first, you can use array for this:
<?php
if ($handle) {
$lines = [];
while (($line = stream_get_line($handle, 4096, "</br>")) !== false)
{
$lines[] = $line;
}
$reversed = array_reverse($lines);
echo join('<br>' $reversed);
fclose($handle);
}
But if you just want to display lines as they are in the files, just simplify the code:
<?php
if ($handle) {
$lines = [];
while (($line = stream_get_line($handle, 4096, "</br>")) !== false)
{
echo $line . '<br>';
}
fclose($handle);
}