简体   繁体   English

PHP字符串不连接

[英]PHP strings not concatenating

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. 我正在使用自定义行分隔符逐行读取PHP中的文件,但是我很难将行字符连接到字符串之后。

$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. 你用每个while循环迭代覆盖$newhtml值。所以,你只会在迭代结束后得到最后一个值。 As I understand your requirement, you want to concatenate every line to the $newhtml variable. 据我了解您的要求,您希望将每一行连接到$newhtml变量。 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 在等号前面加一个额外的点( . ),再次删除{$ newhtml}变量的不必要用法

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM