csv2xml





17
Date Submitted Mon. Oct. 9th, 2006 9:57 PM
Revision 1 of 1
Helper inxilpro
Tags Convert | CSV | PHP | XML
Comments 1 comments
This function converts a CSV file to a simple XML file.

<?php
/**
 * Converts a CSV file to a simple XML file
 *
 * @param string $file
 * @param string $container
 * @param string $rows
 * @return string
 */

function csv2xml($file, $container = 'data', $rows = 'row')
{
        $r = "<{$container}>\n";
        $row = 0;
        $cols = 0;
        $titles = array();
       
        $handle = @fopen($file, 'r');
        if (!$handle) return $handle;
       
        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
        {
             if ($row > 0) $r .= "\t<{$rows}>\n";
             if (!$cols) $cols = count($data);
             for ($i = 0; $i < $cols; $i++)
             {
                  if ($row == 0)
                  {
                       $titles[$i] = $data[$i];
                       continue;
                  }
                  
                  $r .= "\t\t<{$titles[$i]}>";
                  $r .= $data[$i];
                  $r .= "</{$titles[$i]}>\n";
             }
             if ($row > 0) $r .= "\t</{$rows}>\n";
             $row++;
        }
        fclose($handle);
        $r .= "</{$container}>";
       
        return $r;
}
?>
 

$xml = csv2xml('/home/user/myfile.csv', 'people', 'person');
 

<people>
     <person>
          <name>John Smith</name>
          <zip>19100</zip>
     </person>
     <person>
          <name>Jane Doe</name>
          <name>19200</name>
     </person>
</people>
 

Chris M

Comments

Comments Reg Code
Wed. Aug. 8th, 2007 2:31 AM    Newbie php_help

Voting