So reading CSV files is handy and
we were able to use that data to display a suggestion page.
But what if I want to add more suggestions?
I'm always discovering new things and meeting new people.
So, I'm sure that I will have more suggestions in the future.
We could open the CSV file directly, but
that wouldn't work if I wanted to fill out a form that adds a person.
So let's look at using PHP to add an additional line to our CSV file.
Let's create a new file in the inc directory.
We'll name this write_csv.php.
We'll start by creating an array for the new contact.
We'll be using the form data from our add person form.
So, we want to filter our input.
First.
FILTER_SANTIZE_STRING, Last website, Twitter and image.
The website and the image will actually be URLs.
So, we can change this to FILTER_SANITIZE_URL.
Now use fopen to open our CSV file.
Once again, wrapping it in an if statement.
We'll need to go up one level before we enter data/csv/people.csv.
This time we'll use a for the mode meaning append.
It opens the file and places the file pointer at the end of the file.
And fclose.
We can now use fputcsv.
Passing the file handler just like we did for the fgetcsv.
This time we also passed the new array.
And we'll finish off this file by redirecting to the people page.
Let's give this a try in the browser.
Go to Add Person, and fill out the form.
I'm going to add the Treehouse CEO, Ryan Carson.
He's a great person to follow.
Let's grab his profile picture from Twitter.
If you right click, you can copy image address.
We were redirected to the People page, but it didn't show up right.
So, let's take a look at the CSV file.
We can't read CSV files in Workspaces, so we need to rename it first.
We'll change this to txt.
The problem is that there is no new line between the last person and Ryan.
If the file doesn't end on a new line when we try to append, this could be a problem.
Let's delete this edition and rename the file again.
I'm going to show you how to check for a new line.
So, let's make sure this does not end on a new line.
First, we need to be able to read, as well as write.
So, let's add a plus to the mode.
Before we call fputcsv, we're going to use the fseek function.
This will allow us to move the file pointer.
The fseek function accepts three parameters, the file handler,
the offset, which in this case we want to move back one, so
-1, and wents, which tells the point where you are starting from.
We'll use SEEK_END.
Because we want to go back one byte from the end of the file.
Now, we can check if our file ends in a new line.
And if not, add a new end of line character.
If fgets.
Is not equal to the end of line.
Then we're going to fputs.
A new end of line.
Let's go back to the browser and resubmit the form.
This time, our people page shows the new suggestion
properly because it was placed on its own line.