문제

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

도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top