title: PHP exporting several excel files
body: <p>I'm trying to export several tables from a database and creating a excel file for each table using PHP. The loop however is &quot;bugged&quot;. Instead of creating a new file for each loop it just puts all data into the same file.</p>
  <p>The code:</p>
  <pre class="lang-php prettyprint-override"><code>  foreach ($pdo-&gt;query(&quot;SHOW TABLES;&quot;) as $allTables) {
      $table = $allTables[0];
  
      $allDataStmt = $pdo-&gt;prepare(&quot;SELECT * FROM $table;&quot;);
      $allDataStmt-&gt;execute();
  
      $fieldcount = $allDataStmt-&gt;columnCount();
  
      $col_title = &quot;&quot;;
      $data = &quot;&quot;;
      for ($i = 0; $i &lt; $fieldcount; $i++) {
        $col = $allDataStmt-&gt;getColumnMeta($i);
        $column = $col['name'];
        $col_title .= '&lt;Cell ss:StyleID=&quot;2&quot;&gt;&lt;Data ss:Type=&quot;String&quot;&gt;' . $column . '&lt;/Data&gt;&lt;/Cell&gt;';
      }
  
      $col_title = '&lt;Row&gt;' . $col_title . '&lt;/Row&gt;';
  
      while ($row = $allDataStmt-&gt;fetch(PDO::FETCH_NUM)) {
        $line = '';
        foreach ($row as $value) {
          if ((!isset($value)) or ($value == &quot;&quot;)) {
            $value = '&lt;Cell ss:StyleID=&quot;1&quot;&gt;&lt;Data ss:Type=&quot;String&quot;&gt;&lt;/Data&gt;&lt;/Cell&gt;\t';
          } else {
            $value = str_replace('&quot;', '', $value);
            $value = '&lt;Cell ss:StyleID=&quot;1&quot;&gt;&lt;Data ss:Type=&quot;String&quot;&gt;' . $value . '&lt;/Data&gt;&lt;/Cell&gt;\t';
          }
          $line .= $value;
        }
        $data .= trim(&quot;&lt;Row&gt;&quot; . $line . &quot;&lt;/Row&gt;&quot;) . &quot;\n&quot;;
      }
  
      $data = str_replace(&quot;\r&quot;, &quot;&quot;, $data);
  
      header(&quot;Content-Type: application/vnd.ms-excel;&quot;);
      header(&quot;Content-Disposition: attachment; filename=&quot; . $table . &quot;.xls&quot;);
      header(&quot;Pragma: no-cache&quot;);
      header(&quot;Expires: 0&quot;);
    }
  }
  </code></pre>
  <p>If I kill the loop after the first iteration it exports the data correctly from ONE table. If I let the loop run it just loads the same file with the data and the file becomes corrupted. I can't even open it in Excel.</p>
  <p>What am I missing? Been stuck with this for hours.</p>
  <p>Thank you!</p>