473,320 Members | 2,117 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

PHP fwrite() keeps doubling document length

5
Hey all,

Sorry to be the noob with two posts asking a question, but I've been fighting with this for a couple days now, and as far as I can tell, this should be working, but PHP isn't my main language, so I'm sure there's something being missed.

I've made a small program that allows the user to first select a country, then a state/province, and finally add a city to that location. So, when a new city is submitted, I load the .TXT file containing all the other cities belonging to that region into an array, add the new city to the end of that array, sort() it, the write it to the text file by way of while loop.

What's happening though is that when the first city is added, it has one city added to the file, and a carriage return (because of the "\r\n"). When the second city is added, it has the first two cities, followed by two carriage returns (making four lines). When the third city is added, it starts with four carriage returns, three cities, then one carriage return (making eight lines). And it just keep going on like that, doubling the number of lines every time.

[PHP] $country = file ('../../country/country.txt'); //loads all the saved countries into an array
$cou = count ($country);
//First, determine the location of the list of states or provinces for the selected country
$x = $cou - 1;

//we have to knock off the blank space at the end of the variable if it is not the last place in the array
$flat_cnt = trim($country[$_COOKIE['country']]);

$state = file ('../../country/'.$flat_cnt.'/states.txt');
$sta = count ($state);
$flat_sta = trim($state[$_COOKIE['state']]);

$cities = file ('../../country/'.$flat_cnt.'/'.$flat_sta.'/cities.txt');
$cit = count ($cities);//sets a variable to the number of items in the array
$x = 0;
if ( isset ($_COOKIE['city']))
{
print ($cities[$_COOKIE['city']]);
print ('<form method="post" action="post.php"><input type="submit" name="newcity" value="Reselect State" /></form>');
}
else
{
//Print out selection box
print ('<br /><br /><b>Please Enter A New City:</b><br />');
print ('<form method="post" name="submitCity"><input type="text" name="city" size="100"><br /><input type="submit" name="submitCity" value="Add New City" /></form>');
}

if (isset ($_POST['submitCity'])) //handle form.
{
if ($fp = fopen ('../../country/'.$flat_cnt.'/'.$flat_sta.'/cities.txt', 'w+')) //try to open the file. 'w+' means a new file will be created if needed and old files will be overwritten with new contents
{
//Add entered city into cities array
$cities[$cit] = $_POST['city'];
//make the cities array alphabetical
sort($cities);

flock ($fp, LOCK_EX);//lock the file so multiple users can NOT edit file simultaneously by accident
//Write the $cities array to the file
$z = 0;
while ($z <= $cit)
{
fwrite ($fp, "$cities[$z]\r\n");
$z++;
}
flock ($fp, LOCK_UN);//unlocks the file so another user can add cities
fclose ($fp); //close the file

//print a message
print "<p><font color=red><b>The new city, </font><font color=black>".$_POST['city']." </font><font color=red>has been successfully added!</b></font></p>";
}
else //Could not open the file
{
print "<p>The city could not be stored due to a system error.</p>";
}
}[/PHP]

Any help you can offer will be greatly appreciated (o^_^o)

~Xean
Mar 22 '08 #1
3 2278
ronverdonk
4,258 Expert 4TB
Are you sure that you do not have an "\r\n" already in your $cities array read in from the original text file? That would double the output, since you also add that with your ourput.

Ronald
Mar 22 '08 #2
Xean45
5
Are you sure that you do not have an "\r\n" already in your $cities array read in from the original text file? That would double the output, since you also add that with your ourput.

Ronald

Thanks Ronald! Boy, my face is red. Logically, that should have made sense. I just used the str_replace("\r\n","",$variable); to cure that right as rain.

~Xean
Mar 25 '08 #3
ronverdonk
4,258 Expert 4TB
Don't be emberrassed. Happens to everyone sometimes. At least your problem is solved. See you next time.

Ronald
Mar 25 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Connie Walsh | last post by:
Hi: I gleaned a javascript off of the web: http://www.hypergurl.com/popup.html that sets a cookie everytime someone visits your site. If it is the first visit in x number of days then a...
17
by: SW1 | last post by:
I wrote a small program which does something like tftp - transfering files and some chat, anyway i got a problem with fwrite, here is a snippet of my code: while(length > 0) { putchar('.');...
15
by: Suraj Kurapati | last post by:
Hello, I'm having a rather strange bug with this code: for certain values of 'buf', a segmentation fault occurs when 'free(buf)' is followed by an 'fwrite()'. In the program output, there is no...
10
by: cs | last post by:
if i have typedef struct{ unsigned a; unsigned *b; }tp; i would like to ask if it is ok for the "C standard 89" doing something like this {
4
by: janssenssimon | last post by:
//de structure om de highscores in op de slagen typedef struct score{ char *naam; int veld; int score; struct score *volg; }HIGH; void toonhighscores(void)
6
by: meanster99 | last post by:
Can someone please help me! I have created a db in Access 2003 and the overall file size keeps doubling periodically. Before I noticed this phenomenon the DB was at 65Mb (could have been happening...
10
by: Sheldon | last post by:
Hi, I am trying to learn C from scratch and, though I do know how to program in Python, many things in C are hard to understand - even after reading the examples. I guess because so many...
2
by: alexus | last post by:
fwrite(fopen('temp.xml','w+'), print_r(simplexml_load_string(curl_exec($test))),true); i for some reason get "1" inside of my temp.xml
3
by: anandhmca05 | last post by:
<?php // The data file where messages are stored. include ('messages.txt'); $dataf = "messages.txt"; // Max length of of messages $length = 150; // Number of messages shown.
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.