How to convert data from csv file to HTML?

Some sites has large amounts of information. For more reader-friendly, this data put to table. But what do you do when the size of the table can be above 100 rows? Making and editing this table in default editor like Gutenberg or some like this is really the elusive problem. Yeah, I saw WordPress plugin but it doesn’t updated few years and I think, that better way is resolve this problem it’s clean code without plugins or etc.

Convert CSV to HTML without plugin

Problem: How to convert data from csv file to HTML in Wordpress without plugin?
Solutions: By default, PHP has function fgetcsv for work with CSV files, so all we have left is add little bit of magic 🙂

function convert_csv_to_html( $file_url, $link_title, $link_class ) {
	$file_url = esc_url( $file_url, [ 'http', 'https' ] );
	$file_path = $_SERVER['DOCUMENT_ROOT'] . wp_make_link_relative( $file_url );
		
	if ( ( $handle = fopen( $file_path, 'r' ) ) !== false ) {
		$link_class = ( ! empty( $link_class ) && preg_match( '/^[_a-z0-9- ]+$/', $link_class ) ) ? 'class="' . $link_class . '"' : '';
		$count_rows = 0;
		echo '<table class="table">';
			
    		while ( ( $line = fgetcsv( $handle, 1000 ) ) !== false ) { // Set 1000 Lines Limit
				echo '<tr>';
        			foreach ( $line as $cell ) {
    					if ( $count_rows === 0 ) {
    						// Added Table Header Row
    						echo '<th>' . htmlspecialchars( $cell ) . '</th>';
    					} else {
    						// Added Other Rows
    						if ( filter_var( $cell, FILTER_VALIDATE_URL ) === false ) {
							    echo '<td>' . htmlspecialchars( $cell ) . '</td>';
						    } else {
							    echo '<td><a href="' . esc_url( $cell, [ 'http', 'https' ] ) . '" ' . $link_class . '>' . $link_title . '</a></td>';
						    }
						
					    }
					
				    }
				echo '</tr>';
				$count_rows++;
			}
		fclose( $handle );
		echo '</table>';
	}	
}

As you can see it's simple!

Leave Comment

Your email address will not be published. Required fields are marked *