Lesson 4
Writing Table Data to Files with PHP
Introduction

Welcome to this lesson on writing table data to text files using PHP. In the digital age, storing and sharing data efficiently is crucial, and text files offer a simple and compatible solution for various systems. In this lesson, we'll explore how to write formatted table data into a text file using PHP, leveraging functions such as file_put_contents and fputcsv.

By the end of this lesson, you'll be able to take structured data and write it to a text file using PHP. Let’s dive into this skill and build on what you've learned about parsing tables from text and CSV files.

Recall: Basics of Arrays and File Handling

Before we proceed, let's briefly revisit two key concepts: Arrays in PHP and basic file handling.

  • Arrays: In PHP, arrays are a versatile way to store a collection of data, such as rows in a table. This is fundamental as it helps organize your data into a structured format.

  • File Handling: We have previously covered basic reading operations. Now, we move to writing data. PHP offers straightforward functions such as file_put_contents for writing to text files and fopen along with fputcsv for handling CSV outputs.

These foundational concepts will guide us in the process of writing table data into text files.

Structuring Data for Output

First, let's define a Person class to blueprint our data entries. Each Person object in this class will have properties corresponding to the columns in our table:

php
1class Person 2{ 3 public $name; 4 public $age; 5 public $occupation; 6 7 public function __construct($name, $age, $occupation) 8 { 9 $this->name = $name; 10 $this->age = $age; 11 $this->occupation = $occupation; 12 } 13}

With our structure in place, we can now create an array of Person objects. This array, $data, acts as a collection of rows where each Person instance signifies an individual record:

php
1$data = [ 2 new Person("John", "28", "Engineer"), 3 new Person("Alice", "34", "Doctor"), 4 new Person("Bob", "23", "Artist") 5];

In this example, we've created three Person objects and stored them in an array, each representing a row with fields for name, age, and occupation. This structured approach simplifies adding or modifying rows and facilitates seamlessly writing data to files.

Writing Data with Space Delimiters

Now, let's write the data to a text file with spaces as delimiters using PHP functions. Here's how you can do it:

php
1// Output file path 2$outputTxtFilePath = 'output.txt'; 3 4// Header with spaces 5$txtContent = "Name Age Occupation\n"; 6 7// Prepare content for space-separated TXT file 8foreach ($data as $person) { 9 // Add each person's data as a space-separated line 10 $txtContent .= "{$person->name} {$person->age} {$person->occupation}\n"; 11} 12 13// Write the content to the TXT file 14file_put_contents($outputTxtFilePath, $txtContent);
  • Define the Output Path: The file path is set for output.txt.
  • Prepare the Header: The header "Name Age Occupation" is added to the text content.
  • Format the Data: Each Person object is converted into a space-delimited line using string interpolation.
  • Write to File: file_put_contents writes the content to output.txt, ensuring each entry appears on its own line in the text file.
Writing Data to CSV Format

In addition to writing data to a text file with space delimiters, you can also write the data in a CSV (Comma-Separated Values) format. This approach is slightly different, as it involves using the fopen, fputcsv, and fclose functions to handle the file operations:

php
1// Output file path 2$outputCsvFilePath = 'output.csv'; 3 4// Open the CSV file for writing 5$fileCsv = fopen($outputCsvFilePath, 'w'); 6 7// Header with commas 8fputcsv($fileCsv, ['Name', 'Age', 'Occupation']); 9 10// Iterate over each Person object in the data array 11foreach ($data as $person) { 12 // Write each person's properties 13 fputcsv($fileCsv, [$person->name, $person->age, $person->occupation]); 14} 15 16// Close the CSV file after writing 17fclose($fileCsv);

In this code:

  1. Open the CSV File: We start by opening or creating output.csv using fopen in write mode.

  2. Add the Header: The fputcsv function is used to write a header line, "Name, Age, Occupation", labeling each data column.

  3. Write Each Row: As we iterate through the $data array, each Person object is written as a comma-separated line, utilizing fputcsv, which handles the formatting for us.

  4. Close the File: Once all the data has been written, fclose is called to close the file and ensure all entries are saved correctly.

This method demonstrates a structured way of writing data to a CSV file, highlighting the importance of opening and closing files properly to maintain data integrity.

Lesson Summary

In this lesson, you learned how to effectively structure, write, and verify data stored in a text file using PHP. We started by organizing data using classes and arrays, then employed PHP's file-handling capabilities to write this data with space and comma delimiters.

We encourage you to engage with the practice exercises that follow this lesson. Apply what you've learned to reinforce your understanding and gain confidence. Try experimenting with different data structures, adapt them, and ensure your outputs meet your expectations. Well done on progressing through this important lesson!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.