473,898 Members | 3,371 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PHP fwrite() keeps doubling document length

5 New Member
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.ph p"><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="submitCit y"><input type="text" name="city" size="100"><br /><input type="submit" name="submitCit y" 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>Th e 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 2298
ronverdonk
4,258 Recognized Expert Specialist
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 New Member
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","",$variabl e); to cure that right as rain.

~Xean
Mar 25 '08 #3
ronverdonk
4,258 Recognized Expert Specialist
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
1999
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 popup will appear. It would be great for my application but I can't get it to work. Here is my code:
17
6130
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('.'); //These were for error checking if(length <= bsize) { //Buffer is bigger than remaining File realloc(buffer,length * sizeof(char)); //resize buffer to remain rec = recv(sock,buffer,length,0); //recieve Data
15
3918
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 error reported by 'perror()' and the file is written correctly. /* returns NULL upon failure, or a calloc()ed data upon success */ char* recv_data(int *bytes_read);
10
2300
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
9292
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
1646
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 earlier). It then doubled to around 120Mb, then 241Mb and finally it was at 480Mb!! I had a back-up of the 65Mb version so I just copied the new tables/queries/forms from the latest db (480Mb) into the backup (65Mb) and it was OK for a while until it...
10
2702
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 variations exists. Can someone explain why this variation of fwrite fails: #include <stdio.h> #include <stdlib.h> #define ROW 15 /* In order to have more memory and no segmentation
2
2045
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
2719
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
9841
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10858
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10949
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10484
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9662
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8036
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7187
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6077
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4296
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.