Display Table From CSV [WordPress Shortcode]

Plik csv2table.php

<?php

/*
  Plugin Name: CSV2Table
  Plugin URI: https://pawelkosmala.pl/
  Description:
  Version: 20220925
  Author: Paweł Kosmala
  Text Domain:
  Domain Path: /locale
  License: GNU General Public License
  
 */


    function csv2table_shortcode($attrs, $content='') {
        $file=@$attrs["file"];
        $class=@$attrs["class"];
        $count = 0;
        
        if (($handle = @fopen($file, "r")) !== FALSE) {
            $content.='<table class="'.$class.'">';
            while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
                if ($count==0) {
                    $content.='<thead><tr>';
                    foreach ($row as $col) 
                        $content.='<th>'.$col . "</th>";
                    $content.='</tr></thead><tbody>';
                } else {
                    $content.='<tr>';
                    foreach ($row as $col) 
                        $content.='<td>'.$col . "</td>";
                    $content.='</tr>';
                }

                $count++;
            }
            fclose($handle);
            $content.='</tbody></table>';
        }
        return $content;
    }

    add_shortcode('CSV2Table', 'csv2table_shortcode');
?>

Przykład wywołania kodu

[CSV2Table file=”https://pawelkosmala.pl/wordpress.csv” class=”table table-hover”]

Objaśnienie:

file – Adres url do pliku CSV lub ścieżka do lokalnego pliku CSV

class – nazwy class CSS do ostylowania tabeli

Rezultat tabeli na podstawie danych z pliku CSV

[CSV2Table file=”https://pawelkosmala.pl/wordpress.csv” class=”table table-hover”]

Narzędzia dla copywritera