繁体   English   中英

使用JS和PHP将textarea数据发送到文件并保留换行符

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

我有一个表格,其中有一个文本区域,显示读取文件(通过PHP)的结果; 我要它编辑并按一个按钮,然后将其存储回来

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

保存方式(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
     }

该文件是这样的:

line1=a
line2=b
line3=c

问题是:读取时正确显示所有行; 但是保存时(上述方法),文件显示如下:

line1=aline2=bline3=c

我需要保留文件中的中断吗?

提前致谢

您可以在该文件的输出上使用内置的nl2br()函数:

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

您应该使用POST方法而不是GET。 如果您的文件将包含更多的GET限制,那么您丢失了内容。

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

和PHP文件

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

暂无
暂无

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

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