Convert html table to csv using PHP

By | August 18, 2015

Convert html table to csv using PHP

In this tutorial we are going to see how we can convert html table to csv using PHP. Is it possible??. Yes it is. To convert html table to csv using PHP we have to use the PHP Simple HTML DOM Parser. This PHP Simple HTML DOM PARSER let’s you manipulate HTML in an easy way. This parser requires PHP 5+ and it can be used to find html tags with selectors like jQuery.


Now moving into our topic, let’s see how we can convert the below html table to csv,

Now we have to load the above string($table) to variable using str_get_html() method. Before using this method we need include the PHP simple HTML DOM PARSER.(you can download the php file from here)

Also see Convert html table into csv using jQuery

Then to download the csv file we have to set the headers like below,

Explaining the above function, the first step is to open a php output file with write permission. Second step is to iterate through the html loaded variable and find table row elements. Next step is to find th or td elements, and add it to a array if it exists and using fputcsv() function. Write it to the file and close the file. After closing the file, the file will be downloaded automatically as we set the headers in the beginning of the page. Hope this tutorial helps.

Leave a Reply