<html>
<! WriteFileAsCSV.php                                         >
<! Chapter 10, Oracle Database XE PHP Web Programming         >
<! by Michael McLaughlin                                      >
<!                                                            >
<! This script demonstrates how to write a file as a set of   >
<! comma-separated-values (CSV) lines of data.                >
<head>
<title>
  Chapter 10 : WriteFileAsCSV.php
</title>
</head>
<body>
<?php
  // Declare a file name.
  $file = $_GET["p_name"];

  // Strip any double quotes included on the URL.
  $file = ereg_replace('"',null,$file);

  // Determine file path delimiter.
  if (ereg("(Win32)",$_SERVER["SERVER_SOFTWARE"]))
    $slash = "\\";
  else
    $slash = "/";

  // Declare a fully qualified file name.
  $fname = getcwd().$slash.$file;

  // Declare a two-dimension data set.
  $data = array(array("","","","Cumulative","Cumulative")
               ,array("Month","Frequency","Percent","Frequency","Percent")
               ,array("-------------","-------------","-------------"
			         ,"-------------","-------------")
               ,array("January"  ,"66" ,"3.12","1262","59.7")
               ,array("February" ,"106","5.01","1368","64.71")
               ,array("March"    ,"63" ,"2.98","1431","67.69")
               ,array("April"    ,"60" ,"2.84","1491","70.53")
               ,array("May"      ,"97" ,"4.59","1588","75.12")
               ,array("June"     ,"79" ,"3.74","1667","78.86")
               ,array("July"     ,"86" ,"4.07","1753","82.92")
               ,array("August"   ,"125","5.91","1878","88.84")
               ,array("September","52" ,"2.46","1930","91.3")
               ,array("October"  ,"61" ,"2.89","1991","94.18")
               ,array("November" ,"69" ,"3.26","2060","97.45")
               ,array("December" ,"54" ,"2.55","2114","100"));

  // When the the file exists delete it.
  if (is_file($fname))
    unlink($fname);

  // Calll the function to write a CSV file.
  write_csv_from_array($fname,$data);

  // Define function to write a CSV file.
  function write_csv_from_array($file,$data_array)
  {
    // Declare a read-only file resource.
    if ($fp = fopen($file,'w'))
    {
      // Read the two-dimensional array and write it to a CSV file.
      for ($i = 0;$i < count($data_array);$i++)
        if (!fputcsv($fp,$data_array[$i],","))

      // Close the open file handle.
      fclose($fp);
    }
  }
?>
</body>
</html>
