|
Managing Files
LAB: Reading a CSV File
What is the purpose of the lab?
- Demonstrates how to open and read a CSV file
- Builds a "Model" class which returns a list of products and titles
Copy the file "files_project_products.csv" ...
From the WorkingFiles folder for this chapter, copy the file "files_project_products.csv" into htdocs/sweetscomplete/Model/products.csv
Create a file htdocs/sweetscomplete/Model/Products.php ...
- In the file set up a class with the name "Products"
- Define a public function "getProducts()"
- Define a public function "getTitles()"
Define a public variable $products ...
At the top of the file, inside the class: public $products
Define a function __construct() ...
- Open the file ./Model/products.csv using "fopen()"
- Use a "while()" loop to read until "eof()"
- Use "fgetcsv()" to read one line at a time into an array $row
- Using a foreach loop, convert the numeric array into
an associative array which can then be added to $this->products
Define "getProducts()" and "getTitles()" ...
- getProducts() just needs to return $this->products
- In this getTitles() define a "foreach()" loop using $this->products as $row
- Populate an array $titles assigning $row[2]
- Have the function return $titles
Modify htdocs/sweetscomplete/products.php ...
- At the top of the file add a statement: include "./Model/Products.php"
- Delete the two arrays $titles and $products as they will be replaced
- Create a "products" object: $products = new Products();
- At the top of the file add a line $titles = $products->getTitles()
- Have "$maxProducts" be a count of $titles
- Replace $products with $products->getProducts() in the call to function displayProducts()"
|
|