dongluanan7163 2016-01-13 18:50
浏览 50
已采纳

写入文件时出现意外的PHP换行符

I am trying to make a web based chat room and I am storing messages in a text file. But when writing to the file sometimes the line just breaks and starts a new one mid-string, my code for writing:

$_msg_file=fopen("message.txt","a");
stream_filter_append($_msg_file, 'convert.iconv.UTF-8/OLD-ENCODING');
///WRITE TO FILE
if($_SESSION["class"]==="admin")
{
    fwrite($_msg_file,"<li><b style='color:#FF9393;'>".$_SESSION["name"]."</b> ".$_POST["msg"]."</li>
");
}else {
    fwrite($_msg_file,"<li><b style='color:black;'>".$_SESSION["name"]."</b> ".$_POST["msg"]."</li>
");
}
fclose($_msg_file);

Output: http://pastebin.com/0cucqbTW

My jQuery for posting text:

var data={};
data["why"]="send";
data["msg"]=$(".box_msg").val();
if(data["msg"].length<100 && data["msg"].length>1)
{
$.ajax({
  type:"POST",
  url:"send.php",
  data:data,
  success:function(response)
  {
      $(".box_msg").val("");
  },
  error:function(response)
  {
      $("#chat").text(response);
  }
});
  • 写回答

2条回答 默认 最新

  • duanmu5039 2016-01-13 19:08
    关注

    What you have is linebreak characters that you can't see but that are being sent within the $_POST value, as mentioned by Marc B.

    The work around to this is to remove the PHP End of Line Characters, which are handily referenced as PHP_EOL.

    (Personally I would also reference array keys in single quotes as double quotes effects quote references and such within the array values)

    So

    $_POST['msg'] = str_replace(PHP_EOL, '', $_POST['msg']);
    // str_replace($search,replace,subject);
    

    This will remove system used line breaks from the string, before you can then save to the file. You can additionally replace standard line break [type character]s such as and ( is not actually a linebreak as such, exactly) in case they're different from the PHP_EOL value :

    Also suggested you save the changes as another variable rather than the original POSTed data.

    $breaks = array("
    ","",PHP_EOL);
    $strippedMessage = str_replace($breaks, '', $_POST['msg']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 swiftui @query 报错
  • ¥50 怎么解决刷卡或扫码后,点击软件输入框,win10屏幕键盘不会自动弹出的问题
  • ¥15 如何使用arcgispro的训练深度模型,发现water和nowater精度为0?(相关搜索:深度学习)
  • ¥20 matlab作业不太懂呀有问题能给个代码吗
  • ¥15 自制电路图为何无法驱动ESP01S?
  • ¥15 前端加access数据库
  • ¥15 ARCGIS 多值提取到点 ERROR 999999
  • ¥15 mysql异常断电, [MY-011971] [InnoDB]
  • ¥15 uni.onBluetoothDeviceFound熄屏不运行
  • ¥15 求PHDA糖尿病并发症数据集,有偿