Joe C.
Joe C.

Reputation: 29

Line breaks not working in my php program?

When I write a string to the text file "words.txt" in my php program, the line breaks(\n, <br>), do not work and everything I read from the file appears on one line.

I have tried using <br />, /n, \n, <br>. I have tried putting them in different places(where I write the file, and where I read the file).

<!DOCTYPE html>
<html>
    <head>
        <title>Glossary</title>
    </head>

    <body>
        <form action="index.php" method="post">
            <input type="text" name="word">
            <input type="submit" value="submit">
        </form>
    </body> 
</html>
<?php
    $word = $_POST['word'];
    $outPutString = $word.'<br>'; 

    $fp = fopen('words.txt', ab);
    flock($fp, LOCK_EX);
    fwrite($fp, htmlspecialchars($outPutString), strlen(outPutString));
    flock($fp, LOCK_UN);
    fclose($fp);    
?>
<?php

    $fo = fopen('words.txt', rb);
    flock($fo, LOCK_SH);
    while(!feof($fo)) {
        $words = fgets($fo);
        if(!feof(fo)){
            echo htmlspecialchars($words)."<br />";
        }
    }
    flock($fo, LOCK_UN);
    fclose($fo);
?>

Upvotes: 0

Views: 159

Answers (1)

Yoko Ishioka
Yoko Ishioka

Reputation: 161

You're saving to a text file, so it can't render HTML or JavaScript. Try saving with "html" if you want to see the line breaks.

<?php
    $word = $_POST['word'];
    $outPutString = $word.'<br>'; 

    $fp = fopen('words.**html**', ab);
    flock($fp, LOCK_EX);
    fwrite($fp, htmlspecialchars($outPutString), strlen(outPutString));
    flock($fp, LOCK_UN);
    fclose($fp);    
?>
<?php

    $fo = fopen('words.**html**', rb);
    flock($fo, LOCK_SH);
    while(!feof($fo)) {
        $words = fgets($fo);
        if(!feof(fo)){
            echo htmlspecialchars($words)."<br />";
        }
    }
    flock($fo, LOCK_UN);
    fclose($fo);

?>

Upvotes: 2

Related Questions