import/export a csv file in php

To import a CSV file in php, we can use the following code:

<html>
<body>
<?php
$fcontents = file ("uploads/marks.csv"); 

//A:\AAA\www\web\uploads\marks.csv
?>
<table border="1">
<?php
 for($i=0; $i<sizeof($fcontents); $i++) 
  { 
    
      $line = trim($fcontents[$i]); 
    

      $arr = explode(",", $line); 
    ?>
    <tr>
    <td><?php echo $arr[0]; ?></td>
    <td><?php echo $arr[1]; ?></td>
    <td><?php echo $arr[2]; ?></td>
    <td><?php echo $arr[3]; ?></td>
    </tr>
    <?php
    
  
     
  }
  ?>
  
  </table>
  
  </body>
  </html>

To export data into a CSV file in php, we can use the following code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>

</head>
<body>
<?php include("db/opendb.php"); 
$filepath = "uploads/stdrecord.csv";

$fp = fopen("$filepath", "w"); 

$query = "select * from stdrecord";
$stmt = $conn -> prepare($query);
$stmt -> execute();

$removables = array("\r\n", "|", ",",  "\t", "'" ,"\"" , "\\");

while($row = $stmt -> fetch())
{
$row0 = str_replace($removables, "", $row[0]);  
$row1 = str_replace($removables, "", $row[1]);  
$row2 = str_replace($removables, "", $row[2]);  
fwrite($fp, "$row0,$row1,$row2" . chr(13) . chr(10));
}
fclose($fp); 
$conn = NULL;
?>
</body>
</html>

 

Add a Comment

Your email address will not be published. Required fields are marked *