title: Export database table to csv using WordPress page and php
body: <p>I have been trying to make a Wordpress page that will export .csv file with the data from my table "statistics". This script below is working perfectly on localhost if I put it in .php file.</p>
  
  <p>But in Wordpress, it does not work my way. I have put this script in a separate page using plugin for insert php. It downloads .csv file when I access this page, but the data inside is not the data from table. It gives  data, with div tags and errors. I tried also other script from Exchange, and again, it returns this strange file, so obviously the problem is in WordPress and my understanding of the same.</p>
  
  <p><strong>CODE</strong>: I put this script on www.mydomain.com/export (this is wordpress page).</p>
  
  <pre><code>[insert_php]
  global $wpdb;
  $result = $wpdb-&gt;get_results('SELECT * FROM statistics', ARRAY_A);
  
  header('Content-Type: text/csv');
  $date = date("Y-m-d H:i:s");
  header('Content-Disposition: attachment;filename=EXPORT_' . $date . '.csv');
  
  foreach ($result as $row) {
      if ($row) {
          exportCsv(array_keys($row));
      }}
  while ($row) {
      foreach ($result as $row) {
              exportCsv($row);
      }}
  function exportCsv($rows) {
      $separator = '';
      foreach ($rows as $row) {
          echo $separator . $row;
          $separator = ',';
      }
      echo "\r\n";
  }
  [/insert_php]
  </code></pre>
  
  <p>What am I missing? How to make this happens? I want to make an export of one table in MySQL that will export it nicely formatted in .csv file, so users can download it on computer.</p>
  
  <p>Export database table to csv using WordPress page and php.</p>