Page 1 of 1

Outputting XML

Posted: Tue Feb 26, 2008 10:54 pm
by guitmanjo
I'm trying to convert a few downloaded .csv logs from a stats service to simple xml to use with FusionCharts. I found this code which looks promising at http://www.bytemycode.com/snippets/snippet/448/ I'm showing my ingorance but assuming it works I'm not sure how to execute it so that the xml is output. It would be a great plus if it was directly output and saved to a file. Could anyone give me a hand?

Code: Select all

<?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;
}
?>

Code: Select all

$xml = csv2xml('/home/user/myfile.csv', 'people', 'person');
This is the supposed output:

Code: Select all

<people>
     <person>
          <name>John Smith</name>
          <zip>19100</zip>
     </person>
     <person>
          <name>Jane Doe</name>
          <name>19200</name>
     </person>
</people>
I presume the csv file needs to look similar to this:

Code: Select all

name,zip
John Smith,19100
Jane Doe,19200
I can echo $xml, but it isn't formatted.

I'd appreciate any help you could offer

Re: Outputting XML

Posted: Wed Feb 27, 2008 9:38 am
by guitmanjo
If the following:

Code: Select all

<?php 
// Load Functions. 
require_once( 'convert.php' ); 
echo $xml = csv2xml('myfile.csv', 'people', 'person');
?>
Outputs:

Code: Select all

John Smith 19100 Jane Doe 19200
Does that mean the csv2xml function is failing, or is echo simply the wrong way to request display of the data?