<?php
session_start();
include 'myFunctions.php';
 
if (isset($_GET['file'])) {
  $file = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_SPECIAL_CHARS);
}

//$fp = fopen('php://output', 'w');
 
       $sql = "SELECT * FROM countries";
  $num_rows = RecordsCount($conn,$sql);
    $result = mysqli_query($conn, $sql);
 
$header="" ;
for($i=0;$i<=4;$i++)
{
	    $colObj = mysqli_fetch_field_direct($result,$i);                            
		$col = $colObj->name;
    $header .= $col.";" ;
} 
echo $header . "\n";
  
$filename = 'countries.xls';

//Send the correct headers to the browser so that it knows
//it is downloading an Excel file.
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename");  
header("Pragma: no-cache"); 
header("Expires: 0");
 
//Define the separator line
$separator = "\t";
$separator = ";";

// $header=str_replace("," ,$separator, $header);

 // fputcsv($fp, $header);
 
//If our query returned rows
if(!empty($num_rows)){
   
    //Dynamically print out the column names as the first row in the document.
    //This means that each Excel column will have a header.
   //  echo implode($separator, array_keys($rows[0])) . "\n";
    $irow=0;
    //Loop through the rows
 //  $row = mysqli_fetch_row($result);
 //  echo implode($separator, $row) . "\n";
   
    while ($row = mysqli_fetch_row($result)) {
      //   printf ("%s (%s)\n", $row[0], $row[1]);
		//$row = str_replace($separator . "$", "", $row);
		//$row= preg_replace("/\r\n|\n\r|\n|\r/", " ", $row);
		//$row = trim($row);
        //Clean the data and remove any special characters that might conflict
       // foreach($row as $k => $v){
        //    $row[$k] = str_replace($separator . "$", "", $row[$k]);
        //    $row[$k] = preg_replace("/\r\n|\n\r|\n|\r/", " ", $row[$k]);
        //    $row[$k] = trim($row[$k]);
       // }
        
        //Implode and print the columns out using the 
        //$separator as the glue parameter
		//echo  $row[0]."\t ".$row[1]."\t ".$row[2]." ". "\n";
		
        echo implode($separator, $row) . "\n";
    }
}
mysqli_free_result($result);
 
?>