CRISTICODES / PHP / Verify CSV integrity

Example code:

    <?php
    // Verify CSV integrity from URL if it contains the specified header columns
    function verifyCsvIntegrity($url) {

        $headerColumns = ['Cod produs', 'Denumire', 'Categorie principal', 'Descriere produs', 'Imagine 1', 'Pret 2(RON)', 'Stoc'];

        // Fetch the CSV file from the URL
        $csvData = file_get_contents($url);

        // Convert the CSV data into an array of rows
        $rows = str_getcsv($csvData, "\n");

        // Get the header row
        $headerRow = str_getcsv($rows[0], ",");

        // Initialize an array to store error lines
        $errorLines = [];

        // Check if the header row contains all the required columns
        foreach ($headerColumns as $column) {
            if (!in_array($column, $headerRow)) {
                echo "Error: Missing column - $column\n";

                // Store the error line
                $errorLines[] = 1; // Header row line number is 1
            }
        }

        // Verify CSV integrity for all data in specified header columns
        for ($i = 1; $i < count($rows); $i++) {
            $rowData = str_getcsv($rows[$i], ",");

            // Check if the row has the same number of columns as the header row
            if (count($rowData) != count($headerRow)) {
                echo "Error: Invalid row - $rows[$i]\n";

                // Store the error line
                $errorLines[] = $i + 1; // Adding 1 to account for header row
            }
        }

        // If there are no errors, display a success message
        if (empty($errorLines)) {
            echo "CSV integrity verification successful. No errors found.\n";
        }

        // Return the error lines
        return $errorLines;
    }

    // Report errors
    function reportErrors($errors) {
        foreach ($errors as $error) {
            echo "Error on line $error\n";
        }
    }

    // Example usage
    $url = 'test.csv';
    $errors = verifyCsvIntegrity($url);
    reportErrors($errors);
    ?>