Checking CSV File Header

Prima pagină » Blog » Checking CSV File Header

Checking CSV File Header

Introduction

In this code, we are checking the header of a CSV file to ensure it matches the expected header. If the header is correct, it is written to a new CSV file called „test-result.csv”. If the header is not in the exact order, the columns are arranged and then written to the „test-result.csv” file.

Key Concepts

  • CSV file: A CSV (Comma Separated Values) file is a plain text file that stores tabular data (numbers and text) in plain text form, with each line representing a row and each value separated by a comma.
  • Header: The header row in a CSV file contains the names of the columns or fields in the data.

Code Structure

The code follows a structured approach to check and arrange the header of a CSV file. It consists of the following sections:

  1. Declaration of expected and actual headers.
  2. Opening the CSV file and reading the first row (header row).
  3. Checking if the header row matches the expected header.
  4. Writing the header row to the „test-result.csv” file if it matches the expected header.
  5. Arranging the columns if the header is not in the exact order.
  6. Writing the arranged header to the „test-result.csv” file.

Code Examples

<?php
$expectedHeader = ['Reference', 'Name', 'Category', 'Description', 'Image', 'Price (tax incl.)', 'Quantity'];
$actualHeader = [];

if (($handle = fopen($csvFilePath, 'r')) !== FALSE) {
    // Read the first row of the CSV file
    $headerRow = fgetcsv($handle);

    // Check if the header row has the exact columns in the exact order
    if ($headerRow === $expectedHeader) {
        // If the header is correct, write it to the test-result.csv file
        $resultFilePath = 'test-result.csv';
        $resultHandle = fopen($resultFilePath, 'w');
        fputcsv($resultHandle, $headerRow);
        fclose($resultHandle);
    } else {
        // If the header is not in the exact order, arrange the columns and write to the test-result.csv file
        $arrangedHeader = [];

        foreach ($expectedHeader as $column) {
            $index = array_search($column, $headerRow);
            if ($index !== false) {
                $arrangedHeader[] = $headerRow[$index];
            }
        }

        $resultFilePath = 'test-result.csv';
        $resultHandle = fopen($resultFilePath, 'w');
        fputcsv($resultHandle, $arrangedHeader);
        fclose($resultHandle);
    }

    fclose($handle);
}