Question

I am using a popular plugin called simple_html_dom.php, for exporting HTML to CSV with following code:

  <?php

  include "simple_html_dom.php";
  $html = file_get_html('http://siteurl.com');

  header('Content-type: application/ms-excel');
  header('Content-Disposition: attachment; filename=sample.csv');

  $fp = fopen("php://output", "w");

  foreach ($html->find('tr') as $element) {
      $td = array();

      foreach ($element->find('th') as $row) {
          $td[] = $row->plaintext;
      }

      fputcsv($fp, $td);
      $td = array();

      foreach ($element->find('td') as $row) {
          $td[] = $row->plaintext;
      }

      fputcsv($fp, $td);
 }

 fclose($fp);

 ?>  

Everything works fine, except that an empty row is inserted after each row.

What could be the issue?

Attached is the screenshot of my CSV below.

screen shot of my exported csv

Was it helpful?

Solution

I guess you have only the first row having header cells... Trying to get data from <th> in every row will return nothing, wich explains empty rows you're getting...

You can simply rearrange/change your code accordingly... For example replace your big loop with:

$td = array();

foreach ($element->find('tr th') as $th) {
    $td[] = $th->plaintext;
}

fputcsv($fp, $td);


foreach ($element->find('tr td') as $td) {
    $td[] = $td->plaintext;
}

fputcsv($fp, $td);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top