Export to Word from PHP doesn't carry headers beyond first page

2.2k Views Asked by At

I exported data from a PHP page to a Word document but the header is not available in all pages.

Header is present in the first page but not in the other pages of the Word document.

Here is my code,

function changeDetails()
{
    $bType = $this->input->post('textvalue');
    if ($bType == "word")
    {
        $this->load->library('table');
        $data['countrytoword'] = $this->AddEditmodel1->export();
        $this->table->set_heading('Name','Country','State','Town');
        $out =  $this->table->generate($data['countrytoword']); 
        header("Content-Type: application/vnd.ms-word");
        header("Expires: 0");
        header("Cache-Control:  must-revalidate, post-check=0, pre-check=0");
        header("Content-disposition: attachment; filename=$cur_date.doc");
        echo '<br><br>';
        echo '<strong>CountryList</strong><br><br>';
        print_r($out);
    }
}
<? if(isset($countrytoword)) { ?>
  <table align="center" border="0">
    <tr>
      <td>Name</td>
      <td>Country</td>
      <td>State</td>
      <td>Town</td>
    </tr>
    <? foreach($countrytoword as $dsasffd) { ?>
      <tr>
        <td><?= $dsasffd['dbName'] ?></td>
        <td><?= $dsasffd['dbCountry']; ?></td>
        <td><?= $dsasffd['dbState']; ?></td>
        <td><?= $dsasffd['dbTown']; ?></td>
  <? } } ?>
    </tr>
  </table>
3

There are 3 best solutions below

1
On

If you mark the header row(s) with a <thead> element you should get what you want. So this code becomes

 <table align="center" border="0"> 
 <thead>
 <tr> 
  <td> 
   Name 
  </td> 
  <td> 
   Country 
  </td> 
  <td> 
   State 
  </td> 
  <td> 
   Town 
  </td> 

 </tr> 
 </thead>
0
On

Why Microsoft Word?

Now, two solutions:

  1. If you name the file correctly, and set your MIME type correctly, you may be able to get MS Word to open the HTML file, just as you can from the desktop, when you use the File → Open dialog.

  2. Another option is to generate LaTEX, then use latex2rtf to make RTF. There are HTML to RTF converters, and RTF is simple enough that you could make it, but the LaTEX is easier to make than RTF and the quality seems to be better than HTML to RTF.
    Use a System call to run the application, naming the file using a UUID if the data is sensitive, and then redirect. You would not even need to make the headers, as your web server should know what to do with an RTF already.

0
On

don't know about hearder but what kinda loop is this u r using

<? foreach($countrytoword as $dsasffd) { ?>
      <tr>
        <td><?= $dsasffd['dbName'] ?></td>
        <td><?= $dsasffd['dbCountry']; ?></td>
        <td><?= $dsasffd['dbState']; ?></td>
        <td><?= $dsasffd['dbTown']; ?></td>
  <? } } ?>

the TR tag is not closing(except last one) anywhere.