如何消除PHP中的fgets函数的换行符? [英] How do I eliminate line break from fgets function in PHP?

查看:652
本文介绍了如何消除PHP中的fgets函数的换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PHP'fgets'函数制作一个从平面文件数据库调用图像名称的图库。图库中有不同的部分,每个部分都有自己的默认图像以及用户可以从中选择的一小部分图像。一切工作正常,除了一个按钮。



我有一个按钮,应该使用Javascript OnClick将所有图库重设为其默认图像。它的工作原理与我想要的一样,只需一个小小的顺序:它将行结束处的换行符与行中的字符复制,打破Javascript。



违规代码:

  function back(){
document.getElementById('back')。className = '背部';
document.getElementById('one')。className ='cellcont';

//这应该输出正确的javascript,但不是
<?php
$ a = fopen('c.txt','r');
if(!$ a){echo'错误:无法打开文件。';退出;}
$ b = fgets($ a);
echodocument.getElementById('i1')。src ='$ b';;
fclose($ a);
?>






如何输出:

  function back(){
document.getElementById('back')。className ='back';
document.getElementById('one')。className ='cellcont';
document.getElementById('i1')。src = '00 .jpg
';}

正如您所看到的,结尾引号和分号落在下一行,并且这会打破按钮。



使用文件I现在,我可以通过改变fgets($ a)到fgets($ a,7)来解决这个问题,但是我需要让它抓住整条线,这样如果客户决定进入一个名称较长的文件,它不会破坏它们上的图库。

解决方案

你最好的选择是使用php trim ()函数。请参阅 http://php.net/manual/en/function.trim.php

  $ b = trim(fgets($ a)); 


I am attempting to make a gallery that calls the image names from a flat file database using the PHP 'fgets' function. There are different sections in the gallery, each with it's own default image, and a small list of images that the users can select from. Everything is working fine, except for one button.

I have one button on the page that is supposed to reset all the galleries to their default images using Javascript OnClick. It works exactly as I want it to, with one small hitch: It copies the line break at the end of the line allong with the characters on the line, breaking the Javascript.

The offending code:

function back(){
document.getElementById('back').className='back';
document.getElementById('one').className='cellcont';

//This should output the proper javascript, but does not
<?php
$a = fopen('c.txt','r');
if (!$a) {echo 'ERROR: Unable to open file.'; exit;}
$b = fgets($a);
echo "document.getElementById('i1').src='$b';";
fclose($a);
?>

}

How it outputs:

function back(){
document.getElementById('back').className='back';
document.getElementById('one').className='cellcont';
document.getElementById('i1').src='00.jpg
';}

As you can see, the ending quotation mark and the semi-colon falls on the next line, and this breaks the button.

With the files I'm using now, I can get around this problem by changing, "fgets($a)" to, "fgets($a, 7)" but I need to have it grab the entire line so that if the client decides to enter a file with a longer name, it does not break the gallery on them.

解决方案

Your best bet is to use the php trim() function. See http://php.net/manual/en/function.trim.php

$b = trim(fgets($a));

这篇关于如何消除PHP中的fgets函数的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆