Reading files will allow you to retrieve data from manipulation.
But what if you want to share this information with others?
Writing files will allow us to save any changes we make and
also allow us to change settings and update application details.
Building upon the same methods we use for
reading files, lets take a look at a couple different ways to write files.
We're going to combine our states into a single file.
Let's start with the new file named combine.php.
We'll start by opening a new file for writing line by line.
Once again, we use fopen.
We'll call this data/html/combined.html.
This time for the mode, we use w for write.
This tells a function to open the file for writing only.
It places the file pointer at the beginning of the file and
truncates the file to zero length.
This has the effect of erasing the file, so be careful when you use it.
If the file does not exist, it will attempt to create it.
Again, I'll surround the statement with the conditional, so
we don't try to write to a file we can't access.
Then within the conditional, I'll close the file.
We then start writing to the file using the fwrite function.
Like with fgets we pass the handler that we used in the fopen statement.
This time, we also passed the string we want to write.
I want to start with the original states file.
So I can use file_ get_ contents,
data/html/states.html.
Next, I want to write the territories within an opt group.
Again, I can use the file_get_contents, and
this time I'll use data/html/territories.html.
Now, do the same thing for the Armed Forces.
We already finished with fclose.
So, let's add a select and include the file we just wrote so
that we can check this out in the browser.
Great, now we have a single file to use first state dropdown.
If you view the source, you can see that it's a little hard to read
because we don't have proper line breaks.
Let's go back and add those.
A good way to add line breaks to a file is with the predefined constant PHP_EOL.
This will add the correct end of line symbol for
the platform where the script is running.
We'll add this before all but the first write.
Now, we may refresh the source.
Our line breaks show up nicely making the file easier to read.
Let's go back to work spaces and look at writing the entire file at once.