Join Kevin Skoglund for an in-depth discussion in this video Read from a CSV file, part of PHP: Object-Oriented Programming.
- [Narrator] In this movie, we're going to learn how to read from a CSV file using PHP. The way that we read from a CSV file is using a built in PHP function called fgetcsv. It's similar to the function fgets in PHP. Fgets returns a single line from a file, fgetcsv will return a line from a file and parse it as a commented limited set of text. You pass in three arguments, the first is the file handle. When we're working with a file, we have a file handle to work with.
Then we pass in the length, that's the length of the longest possible line. You can either pick a large value like 1,000 or you can use zero to have an unlimited length of line. And then the last argument is delimiter, which is probably going to be just a simple comma. So a string with a comma inside of it, if you omit it, that's what PHP will use by default. So it reads and it parses a line in a file and returns back an array of fields. If it encounters a blank line, it returns an array that has [NULL] as the only value inside. So here's what it might look like.
If you haven't worked with files in PHP before, this'll give you a brief introduction to how it works. We use fopen to open a file, we provide the file name that we want to target, and the fopen function creates a handle that points to that file. And we're going to store that in the variable file. So then I have a loop that says, while we haven't reached the end of the file, that's what feof stands for, that's eof is end of file, f lets it know that it's one of our file functions. So while we haven't reached the end of the file, keep looping. And each time it goes through, it's going to call fgetcsv, it's going to grab a row of data, it's going to parse it and assign it to row.
So row is now equal to an array. We're just going to do some error checking if row happens to be null or if it returns false, then it knows that there was either a blank line or some other kind of problem and it'll just skip to the next line. If it's not a problem though, we're going to take that array and we're going to add it into our data array so we'll now have an array of arrays. And then last thing is to close that file by passing the file handle into fclose. Now this is the simplest version. A slightly more improved version would be to figure out if there's a header row or not.
So here you can see that header starts out being false, and then inside the loop I check to see if header is still false, then that means this first row is the header row. And I want to take those and I want to add them to the header variable and then every other row after that will take that header array and it will combine it with the row data to create an associative array, that's what array combine does. So then we'll have an associative array of key value pairs. So for example, a key for year and a value for 2017, and so on.
So we just get an associative array instead of just a simple array. Let's try adding this to our project, but let's do it in an object-oriented way. The way I'm going to make this object-oriented is I'm going to create a new class that's going to handle this business for us. So inside the classes directory, I'm going to create a new file and I'm going to call it parsecsv.class.php. And inside there, we'll just put our php tags, we'll define the class, which I'm going to call ParseCSV.
So this class is going to be the class that handles the business of parsing. So we're going to use properties to store some of this information. For example, we'll have a public property for file name. Then we'll be able to set the file name and we'll know what to parse. Then we also know that we're going to need to have header and data variables, so let's make private properties for those, header and private data, which will be initialized to an empty array.
So now we have those set up for us. Let's create a construct function, public function __construct, and let's pass in the file name to that. We won't pass in the whole lot of arguments, just one, which is the file name. And if file name is not equal to nothing, then let's set this property for file name equal to file name, okay? So now I have the ability to instantiate it and set its file name at the same time.
And then let's create another method down here, we'll make this one also public and it'll be a function called parse. And when I call parse, what I want to do is I want to take that file name and I want to parse it, and I want to return back the data. So at the end, I'm going to return back this data at the very end. Oops, there we go. So whatever value I've put into that array is going to be the end result. So what do we put in here, how do we parse? Well, we've seen that before, let me just double click this.
I have a little sample here, this is exactly what we were just looking at in the slides. I'm going to copy that, that's included in the exercise files, and I'm going to paste that in. Now, header doesn't need to be set to false right here, I can just remove that, we already have that defined. Data has already been set as well, so I can remove that. Instead of file name just a simple variable, it's now a property, so it's this file name, right? So I'm opening up this file name, I'm setting it equal to the local variable file, while I'm not at the end of the file, I'm going to go through that file and I want to get each line and I want to parse it into a row, right? So now I have a local variable row.
I'm going to check and make sure that there's no problems with that row. Now header is not a local variable header anymore, it's this header. So this header will be equal to the row if we haven't set it before. Otherwise, let me just come down here, let's combine this header with row and then we're going to put it in this data array. All right, let me just unindent these lines a little bit, I got a little confused there. And then finally at the end it'll close the file and it'll return back this data as a result.
Now that we've written it, let's try it out. Let's go over here to bicycles.php and right here above where we have our bicycle being instantiated now, let's create a new instance of our parser, new ParseCSV, and we can pass in the file name, it's inside this private path here. Now remember, we have a constant for private path, so we can use that, PRIVATE_PATH and append that together with /used_bicycles.csv.
That'll give the correct file path to find this used_bicycles.csv file, it'll pass it in to the parser, and then we can ask it to return back a bike array by saying $parser, parse, and that's it. Now we want to check our results, so let's just do something here that does print_r on bike array, it's going to be ugly, but at least let us see the results. Now before we try it out, we want to make sure that we do have access to this ParseCSV.
So intialize.php, you'll either need to have gone through all of the classes so that they're being listed, or you'll need to define it one by one, or you'll need to have auto load in place. One of those needs to be there. Once we have that, we can go back to Firefox, we can reload our page, and look at that. Brand, Trek, model, Emonda, year, 2017, and so on. It's successfully reading and parsing our CSV file and now we have an array that we can work with.
- Defining classes
- Calling methods
- Class inheritance
- Extending and overriding classes
- Accessing and controlling access to properties and methods
- Static properties and methods
- Magic methods: constructor, destructor, and clone
- Creating a PHP OOP project