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 - PHP Tutorial
From the course: Learning the Standard PHP Library
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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
Inspecting single directories with DirectoryIterator6m 52s
-
(Locked)
Inspecting single directories with FilesystemIterator5m 59s
-
(Locked)
Inspecting directories recursively with RecursiveDirectoryIterator6m 58s
-
(Locked)
Getting information about files with SplFileInfo5m 34s
-
(Locked)
Working on text files with SplFileObject8m
-
(Locked)
Using SplFileObject to convert a CSV to an array4m 25s
-
(Locked)
Exporting data to a download file with SplTempFileObject5m 24s
-
-
-
-
-
-
-