Converting csv to XML using php

Below is the code which will show the process of uploading a CSV file & converting it to an XML File with predefined Node structure

File1: index.php

<html>
<body>
<form enctype="multipart/form-data" action="import.php" method="post">
  <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
  <table width="900">
  <tr>
  <td>CSV File Name</td>
  <td><input type="file" name="file" /></td>
  <td><input type="submit" value="Upload" /></td>
  </tr>
  <tr>
      <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
      <td colspan="3">Please note that the fileds in excel sheet should be in Name,Type,Pre-Windows 2000 Logon Name,E-Mail Address,Office</td>
  </tr>
  </table>
</form>
</body>
</html>


File 2: import.php

<?php
error_reporting(1);
$file= fopen("ADUsers.xml", "w");

 $xml="";

 $xml="<ROOTNODE>";
 

  if ( $_FILES['file']['tmp_name'] )
  {
     $fp = fopen($_FILES['file']['tmp_name'], 'r');
   
     $firstline=false;
 
  $r=0;
  $str='';   
 $i=0;
  while (!feof($fp)) {
  
  
    $line = fgetcsv($fp, 4096);
    if (($line != '') &&($firstline==true)) {
   
    $line[2]=str_replace("'","",$line[2]);
   
       
$xml = $xml . "<username>".trim($line[2])."</username>";
      }   
    $firstline=true;
    $i++;
  }
 
   fclose($fp);
 
  $xml=$xml."</ROOTNODE>";
  fwrite($file, $xml);
 fclose($file);

 echo $i. "Records have been converted.<br><br> Please check in your folder for new updated ADUsers.xml";

 }       
  ?>


SAMPLE XML File Generated:

<ROOTNODE>
<username>aashish_mylapally</username>
<username>abbas_kashani</username>
<username>abdul_khadeer</username>
</ROOTNODE>

No comments:

Post a Comment