简体   繁体   中英

Send textarea data to a file using JS & PHP and preserving line breaks

I have a form in which I have a textarea showing the result of reading a file (via PHP); I want it to edit and pressing a button, store it back

<?php 
$salida = file_get_contents($path);
echo "<textarea rows='10' cols='100' id='file' name='file'>" . "$salida" . "</textarea>";
?>

Saving method (JS)

document.getElementById('btn-save').addEventListener('click', function(e) {
        e.preventDefault();
        request({
            method: 'GET',
            url: 'actions/save.php?file='+document.getElementById('file').value
        }, function(ok) {
            ...      
        }, function(ko) {
            ...
        });
    });

save.php

<?php
    $TEMP = '/tmp/file.tmp';

    if (isset($_GET['file']))
    {
        $fh = fopen($TEMP, "w+");
        $string = $_GET['file'];
        fwrite($fh, $string); // Write information to the file
        fclose($fh); // Close the file
     }

The file is like:

line1=a
line2=b
line3=c

Problem is: when reading, it shows all the lines correctly; but when saving (methods above), the file appears like:

line1=aline2=bline3=c

What do I need to preserve the breaks in the file?

Thanks in advance

You could use the built in nl2br() function on the output of that file:

<?php 
    $salida = file_get_contents($path);
    echo "<textarea rows='10' cols='100' id='file' name='file'>" . nl2br($salida) . "</textarea>";
?>

You should use POST method not GET. If your file will contain more then GET limit then you lost content.

document.getElementById('btn-save').addEventListener('click', function(e) {
        e.preventDefault();
        request({
            method: 'POST',
            url: 'actions/save.php',
            data: {content: document.getElementById('file').value}
        }, function(ok) {
            ...      
        }, function(ko) {
            ...
        });
    });

and PHP file

if (isset($_POST['content']))
{
    $fh = fopen($TEMP, "w+");
    $string = $_POST['content'];
    fwrite($fh, $string); // Write information to the file
    fclose($fh); // Close the file
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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