From the course: Learning the Standard PHP Library

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Using SplFileObject to convert a CSV to an array

Using SplFileObject to convert a CSV to an array - PHP Tutorial

From the course: Learning the Standard PHP Library

Start my 1-month free trial

Using SplFileObject to convert a CSV to an array

- A useful feature of the SPL file object class is that it can convert a CSV file into an array. This time we'll create the object from an individual file rather then using an iterator. I've created a blank file to work in, and I've called it fileobject_csv.php. There are two CSV files in the common data folder so let's open that folder and there's cars.csv. If we open that, it's a comma separated values file that contains details of used cars for sale. The other one, cars_tab.csv, if we open that, it contains exactly the same values. The difference is that it uses tabs rather than commas as the delimiter between fields. Using commas is far more common so we'll work with cars.csv first. So let's go back to the working page and we need to create an object, we'll call it $csvfile and it will be a new_SplFileObject( ) and we pass it the path to the file that we want to work with. So that's ('common/data/cars.csv'). Because it's an SPL file object, we can use a foreach loop to go through…

Contents