We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 10449
    • 956 Posts
    Just use your snippet in a doc without any assigned template. You can generate a special header in your snippet instead, see the docs: http://php.net/manual/en/function.header.php

    e.g. your 1st line in the snippet would be:

    header('Content-type: application/vnd.ms-excel');
    
      • 4429
      • 429 Posts
      Here is the snippet

      <?php
      header('Content-type: application/vnd.ms-excel');
      $output = '';//create variable for holding the output
      $sql = $modx->db->query( 'SELECT * FROM `ebmonthlyweb_user_attributes_extended` LIMIT 0, 1000');//define the DB query, in this case the table is named 'tblprojects', add WHERE AND etc. as needed
      $resultArray = $modx->db->makeArray( $sql );//put it into an array
      foreach($resultArray as $item)//go through each record in the array
      
      header("content-type: plain/text");
      header("content-disposition: attachment; filename=$downloadfile");
      header("content-Transfer-Encoding: binary");
      header("Pragma: no-cache");
      header("Expires: 0");
      
      {//start looping through the data array
      $params['gender']=$item['gender'];
      $params['name']=$item['fullname'];
      $params['businessname']=$item['username'];
      $params['sector']=$item['business_type'];
      $params['subscriber']=$item['subscriber'];//set the placeholders, the $params sets the name of the placeholder, the $item is the column name from the DB table
      $params['address']=$item['address'];
      $params['city']=$item['city'];
      $params['county']=$item['state'];
      $params['postcode']=$item['zip'];
      $params['country']=$item['country'];
      $params['phone']=$item['phone'];
      $params['fax']=$item['fax'];
      $params['email']=$item['email'];
      $output.=$modx->parseChunk('databaseTpl', $params, '[+', '+]');//define the chunk name and process the content, here it's ProjectTpl which has the placeholders for the data
      }//finish looping through the data array
      return $output;//now return the output from the processed chunk
      ?>


      It is returning a CSV but is only showing 1 record.

      Manually checking the database shows there are over 100 records/users.
        • 4310
        • 2,310 Posts
        <?php
        header('Content-type: application/vnd.ms-excel');
        header("content-type: plain/text");
        header("content-disposition: attachment; filename=$downloadfile");
        header("content-Transfer-Encoding: binary");
        header("Pragma: no-cache");
        header("Expires: 0");
        $output = '';//create variable for holding the output
        $sql = $modx->db->query( 'SELECT * FROM `ebmonthlyweb_user_attributes_extended` LIMIT 0, 1000');//define the DB query, in this case the table is named 'tblprojects', add WHERE AND etc. as needed
        $resultArray = $modx->db->makeArray( $sql );//put it into an array
        foreach($resultArray as $item)//go through each record in the array
        {//start looping through the data array
        $params['gender']=$item['gender'];
        $params['name']=$item['fullname'];
        $params['businessname']=$item['username'];
        $params['sector']=$item['business_type'];
        $params['subscriber']=$item['subscriber'];//set the placeholders, the $params sets the name of the placeholder, the $item is the column name from the DB table
        $params['address']=$item['address'];
        $params['city']=$item['city'];
        $params['county']=$item['state'];
        $params['postcode']=$item['zip'];
        $params['country']=$item['country'];
        $params['phone']=$item['phone'];
        $params['fax']=$item['fax'];
        $params['email']=$item['email'];
        $output.=$modx->parseChunk('databaseTpl', $params, '[+', '+]');//define the chunk name and process the content, here it's ProjectTpl which has the placeholders for the data
        }//finish looping through the data array
        return $output;//now return the output from the processed chunk
        ?>
          • 4429
          • 429 Posts
          Awesome stuff. Thanks a lot.

          What do i need to extact the table headers too?
            • 4310
            • 2,310 Posts
            Here’s a snippet I just rediscovered, made from some code I found somewhere.
            It will output a csv file with all the column names as a header row then a line for each record, with each field value, no need to specify them.
            Works on any table, choose your mime type (near the bottom).
            <?php
            // MySQL table name, you choose 
            $table = "modx_web_user_attributes";
            exportMysqlToCsv($table);
            function exportMysqlToCsv($table,$filename = 'export.csv')// Output filename, you choose 
            {
                $csv_terminated = "\n";
                $csv_separator = ",";
                $csv_enclosed = '"';
                $csv_escaped = "\\";
                $sql_query = "select * from $table";
            
                // Gets the data from the database
                $result = mysql_query($sql_query);
                $fields_cnt = mysql_num_fields($result);
            
            
                $schema_insert = '';
            
                for ($i = 0; $i < $fields_cnt; $i++)
                {
                    $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
                        stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
                    $schema_insert .= $l;
                    $schema_insert .= $csv_separator;
                } // end for
               
                $out = trim(substr($schema_insert, 0, -1));
                $out .= $csv_terminated;
            
                // Format the data
                while ($row = mysql_fetch_array($result))
                {
                    $schema_insert = '';
                    for ($j = 0; $j < $fields_cnt; $j++)
                    {
                        if ($row[$j] == '0' || $row[$j] != '')
                        {
            
                            if ($csv_enclosed == '')
                            {
                                $schema_insert .= $row[$j];
                            } else
                            {
                                $schema_insert .= $csv_enclosed .
                                str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
                            }
                        } else
                        {
                            $schema_insert .= '';
                        }
            
                        if ($j < $fields_cnt - 1)
                        {
                            $schema_insert .= $csv_separator;
                        }
                    } // end for
            
                    $out .= $schema_insert;
                    $out .= $csv_terminated;
                } // end while
            
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header("Content-Length: " . strlen($out));
                // Output to browser with appropriate mime type, you choose ;)
                header("Content-type: text/x-csv");
                //header("Content-type: text/csv");
                //header("Content-type: application/csv");
                //header('Content-type: application/vnd.ms-excel');
                header("Content-Disposition: attachment; filename=$filename");
                echo $out;
                exit;
            
            }
            ?>
              • 4429
              • 429 Posts
              Worked a treat - thanks very much for this.
                • 4310
                • 2,310 Posts
                smiley