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);