read CSV file in PHP

 PHP code

<!DOCTYPE html>

<html>

<head>

    <title>CSV to HTML Table</title>

    <style>

        table {

            border-collapse: collapse;

            width: 100%;

        }


        th, td {

            border: 1px solid #dddddd;

            text-align: left;

            padding: 8px;

        }


        th {

            background-color: #f2f2f2;

        }

    </style>

</head>

<body>


<?php


function parseCSV($filename) {

    $rows = array();

    if (($handle = fopen($filename, "r")) !== false) {

        while (($data = fgetcsv($handle, 1000, ",")) !== false) {

            $rows[] = $data;

        }

        fclose($handle);

    }

    return $rows;

}


// Specify the path to your CSV file

$csvFile = 'sample.csv';


// Parse the CSV file

$data = parseCSV($csvFile);


// Check if there is data

if (!empty($data)) {

    echo '<table>';

    

    // Output header row

    echo '<tr>';

    foreach ($data[0] as $header) {

        echo '<th>' . htmlspecialchars($header) . '</th>';

    }

    echo '</tr>';


    // Output data rows

    for ($i = 1; $i < count($data); $i++) {

        echo '<tr>';

        foreach ($data[$i] as $value) {

            echo '<td>' . htmlspecialchars($value) . '</td>';

        }

        echo '</tr>';

    }


    echo '</table>';

} else {

    echo 'No data found.';

}

?>


</body>

</html>

------------------------------------------------------------------------------------------------------------------------

Popular posts from this blog

MCSL 216 MCA NEW Practical ~ common questions suggestions

dev chaeatsheet

STRAPI