How to convert a CSV file to an HTML table in WordPress
Some sites have a lot of data, and to make it easier to read, it goes into a table. But what if the table has more than 100 rows? Creating and editing such a table in Gutenberg or any other editor is a real pain. Yes, I saw a WordPress plugin for this, but it had not been updated for a few years, and I think the better way is a little clean code.
Problem: How to convert the data from a CSV file to an HTML table in WordPress without a plugin?
Solution: PHP has the fgetcsv() function for reading CSV files, so all that is left is a little bit of magic 🙂 The client keeps the data in a spreadsheet, exports it as CSV, uploads it to the Media Library, and the table on the site is built from the file.
The function
The first row of the file becomes the table header. A cell that contains a URL becomes a link with the given text and class.
<?php
function convert_csv_to_html( $file_url, $link_title = 'Link', $link_class = '' ) {
$file_url = esc_url_raw( $file_url, array( 'http', 'https' ) );
$file_path = $_SERVER['DOCUMENT_ROOT'] . wp_make_link_relative( $file_url );
if ( ! is_readable( $file_path ) || false === ( $handle = fopen( $file_path, 'r' ) ) ) {
return;
}
$link_class = ( $link_class && preg_match( '/^[_a-z0-9- ]+$/i', $link_class ) ) ? ' class="' . $link_class . '"' : '';
$row_index = 0;
echo '<table class="table">';
while ( false !== ( $row = fgetcsv( $handle, 0 ) ) ) { // 0 = no line length limit
echo $row_index === 0 ? '<thead><tr>' : '<tr>';
foreach ( $row as $cell ) {
if ( 0 === $row_index ) {
// Header row
echo '<th>' . esc_html( $cell ) . '</th>';
} elseif ( false !== filter_var( $cell, FILTER_VALIDATE_URL ) ) {
echo '<td><a href="' . esc_url( $cell ) . '"' . $link_class . '>' . esc_html( $link_title ) . '</a></td>';
} else {
echo '<td>' . esc_html( $cell ) . '</td>';
}
}
echo $row_index === 0 ? '</tr></thead><tbody>' : '</tr>';
$row_index++;
}
fclose( $handle );
echo '</tbody></table>';
}
Call it in a template, for example with the file URL from an ACF File field:
<?php convert_csv_to_html( get_field( 'csv_file' ), 'Download', 'btn btn-sm' );
As you can see, it is simple!
As a shortcode
To put the table into the content, wrap the function in a shortcode. The function prints the table, so its output is captured with a buffer:
<?php
add_shortcode( 'csv_table', function ( $atts ) {
$atts = shortcode_atts( array( 'url' => '', 'link_title' => 'Link', 'link_class' => '' ), $atts );
ob_start();
convert_csv_to_html( $atts['url'], $atts['link_title'], $atts['link_class'] );
return ob_get_clean();
} );
Usage: [csv_table url="https://example.com/wp-content/uploads/2019/10/prices.csv"].
NOTE: The file path is built from DOCUMENT_ROOT and the URL, so the CSV must be on the same server, and WordPress must be installed in the site root. Save the file as UTF-8, otherwise special characters will be broken. Excel saves CSV in the local encoding unless you choose “CSV UTF-8”.