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.
Use rtrim().
Specifically:
rtrim($var, "\r\n");
(To avoid trimming other characters, pass in just newline.)
Your best bet is to use the php trim() function. See http://php.net/manual/en/function.trim.php
$b = trim(fgets($a));
$b = fgets($a);
$b = preg_replace("/[\n|\r]/",'',$b);
I've tried many tests to make this work but can't seem to figure this one out!
A PHP code is called before it sends an email, it checks if placeholders have values in them, then adds them in email. Results I get are all on same line with no line breaks.
Can someone please tell me how to insert a line break in the code?
I've tried the linebreak br with single quotes and double in many places in the code, nothing is working. I've tried the echo code, I get errors.
Each placeholder starts with the IF statement and must end with the value}'; for each one. Where and how can I insert the line break between the IF and value}'; for each?
Thanks a million!
Results come out like this scapbooking20dancing35
instead of:
scapbooking
20
dancing
35
if you guys had to put a line break in this code, how does it go? cheers if($_POST['form']['age'] != '') $modAdminEmailText .= '{age:caption}: {age:value}';
/* Retrieve the admin email text */
$modAdminEmailText = $form->AdminEmailText;
/*Checks if the field has a value and if so, add it to the Email Text*/
if($_POST['form']['hobby'] != '')
$modAdminEmailText .= '{hobby:caption}: {hobby:value}';
if($_POST['form']['age'] != '')
$modAdminEmailText .= '{age:caption}: {age:value}';
/*After the field placeholders are added we will need to replace them with the actual submitted values.*/
$adminEmail['text'] = $modAdminEmailText;
$adminEmail['text'] = str_replace($placeholders, $values, $adminEmail['text']);
been there, done that. Here's what I think is going on.
I've tried the linebreak br ... with single quotes and double.. in many many places in the code, nothing is working.. I've tried the echo code, I get errors, 2 days now no sleep :(
using <br> in your code will only work if you write the e-mail as HTML. Check the documentation for the e-mail library you use to see how you do that.
Now in stead of using <br> you may want to use the \n or \r\n symbol. Beware, that if you use that, then you must enclose your string with double quotes: $somevar."\n"
Alternatively try to use PHP_EOL like this: $somevar. PHP_EOL
I'm not sure how these two methods behave when using string interpolation, but it's worth a try.
I have a script that generates Javascript based on user form inputs. At present the code is outputted to a txt file on the server, but I'd like to put it into a MySql database.
Writing line by line to a txt file is easy with fopen, and helpful with my script due to the way the code is generated and wrapped around user inputs (various loops etc).
However, I'd really like to write the output to a variable, and then send that to the database. However, I can't see any way of accomplishing this?
Im sure it is possible, but the information I've found online only deals with quite basic variable creation.
A dirty solution would be to write to the txt file as I currently do, and then load the text file into a variable and then delete the text file. But this seems silly and clearly a waste of processing time.
Very new to Php so sorry if the above seems dumb.
It's not too difficult, you can declare the variable with the first line and then incrementally write to it, with the \n escape sequence (representing a new line) separating each line. You can size use the PHP_EOL built-in inserted, as commented. The=` assignment operator appends the string following the operator to the variable's value prior to the operation.
$lines = "my first line";
while (condition) {
$lines .= PHP_EOL . "my next line";
}
A derivative way of doing this would be to insert all the lines inside the loop and start with just declaring an empty string.
$lines = "";
while (condition) {
$lines .= "my next line" . PHP_EOL;
}
Note that this method will add an empty newline at the end, which you can trim off of needed.
Alternatively, another way would be to create an array, push to it, and then use the implode function to glue together the array into a string using a newline.
$lines = array();
while (condition) {
array_push($lines, "my next line");
}
$lines = implode(PHP_EOL, $lines);
I am trying to re-activate my php knowledge for the following task:
I have a larger textfile containing unsorted lines of comma separated informations, each value enclosed by a '"'.
Each line can be understood as a single dataset, the first value of the line tells me in which table the row belongs.
Now I need to read the file, sort the lines (so that the lines belonging to the same table are together), detect the different blocks and save them in seperate text files. After that, I can do a fast import into a mysql database using load data from infile..
So, I can open the file and sort the lines via this:
<?php
$lines = file("importfile_unsorted.txt");
natsort($lines);
file_put_contents("importfile_sorted.txt", implode($lines));
?>
This works. But now I get stucked. importfile_sorted.txt looks like this:
"AV1","0","0","0","0","0","0","0","0","0","0","0:0","0:0","0:0"
"AV2","0","0","0","0","0","0","0","0","0","0","0:0","0:0","0:0"
.... [this would be the first block, all these lines should be saved in "av.txt"
In the next line the new block "F" begins with several lines:
"F1","D","D","Deutsch",,,"0","W"
"F4","E","E","Englisch",,,"0","W"
"F7","K","K","Kath.Religionslehre",,,"0","W"
"F8","Ev","Ev","Evang.Religionslehre",,,"0","W"
"F9","Eth","Eth","Ethik",,,"0","W"
... [save all these lines beginning with Fxx into file f.txt and go to the next blocks]
"G1","PhL","PÜG"
"G2","ChL","ChÜ"
..
"K1","5a","5a",,"304","Ma","Wei","0","16","16","5",,,,,"1","1","0",,"0","0","0","0"
"K2","5b","5b",,"303","Wo","Hm","0","32","16","5",,,,,"1","1","0",,"0","0","0","0"
"K3","5c","5c",,"302","Gr","Ro","0","32","16","5",,,,,"1","1","0",,"0","0","0","0"
... and so on. Later, there are blocks with a fixed first column like this:
"PL","Di 1","Ba","Q12","Inf1","CoR1"
"PL","Di 1","Bb","Q12","F","Ü2"
"PL","Di 1","Eg","Q12","L","M23"
...
and
"PLS","Di 1","Am"," frei "
"PLS","Di 1","Bad"," ----"
"PLS","Di 1","Bk"," frei "
...
followed by several other blocks (L1... L97, M, R1... R40, U1... U560).
I know all possible "identifiers" (AVx, Fx, Gx, .. PL, PLS..) of the blocks, but it is also possible that a block is omitted and the input file does not a single line of it at all.
The input file contains about 4000 lines all together, so performance should not be too low (although it's not time-critical, the import is done maybe 10 times a year..).
So, is there a way of getting this done in a "smart" and fast way or should I read the input file line by line, detect and remember the first value, add the current line to a result string and loop until a new first value occurs?
Thanks for your help!
Heiko
Use the built in CSV parser, don't split this manually
http://php.net/manual/en/function.str-getcsv.php
I am currently working on this project which requires me to make a function which dinamically decides the directory name and then creates a simple .txt file in that directory.
my code is as follows:
($destinatario is a string)
$diretorio="../messages/".$destinatario;
if (is_dir($diretorio)) {
;
}else{
mkdir($diretorio);
}
$path=$diretorio."/".$data.",".$assunto.",".$remetente.".txt";
$handle=fopen($path,'w+');
fwrite($handle, $corpo);
fclose($handle);
nevermind the portuguese, but the bottom line is that it should create a .txt file using the naming guidelines i've provided. The funny thing is that when i do this, php creates this weird file whose filename is "01.09.2010 04"
(with no extension at all) which amounts to the first few characters of the actual filename i'd like to create...
edit($data is actually the output from a call to date("d.m.Y H:i"))
Per comment by OP:
[$data is] actually the output of a call to date("d.m.Y H:i")
The problem is the : character. (Still, there may be other illegal characters in the other parts composing the final file name.)
EDIT
The essence of the problem and solution is in the comments to #tchen's answer. Keep in mind that colon is a valid file name character on (some? all?) *nix platforms but is invalid on Windows.
Make sure there's no bad characters at the end of $data. Call trim() on it.
If it's data taken from a file, it may have a '\r' or '\n' at the end of it.
Not related, but make sure your if statements don't have unused conditions:
if (!is_dir($diretorio)) {
mkdir($diretorio);
}
This will also get rid of that blank line with a single terminator ;, I'm sure that isn't right.
Some ideas:
have you tried not using commas in the filename?
Have you checked the return value if fopen and fwrite?
Just to try to isolate the problem
also you can simplify to:
if (!is_dir($diretorio)) {
mkdir($diretorio);
}