tags:

views:

46

answers:

2

I need to upload a file (in this case a csv file) and load the contents of it into the following function:

function csv2xml($file, $container = 'data', $rows = 'row')
{
        $r = "<{$container}>\n";
        $row = 0;
        $cols = 0;
        $titles = array();


        while (($data = fgetcsv($file, 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++;
        }
        $r .= "</{$container}>";

        return $r;
}

This is how im calling the function

csv2xml($_POST['file'], $container = 'wholething', $rows = 'item');

In the form the input box's name is file

I get the following Warning:

  fgetcsv() expects parameter 1 to be resource, null given
+2  A: 

You need to open the file first, eg:

$filePointer = fopen($file, "r"); // read-only

Then use:

while (($data = fgetcsv($filePointer, 1000, ',')) !== FALSE)

to retrieve your data.

Note that you'll probably want to check out PHP's file upload information to make sure you're using the $_FILES array to get your uploaded file. and not just $_POST.

richsage
A: 

@richsage already answered the question. If you still have problems, visit the documentation for a working example. I just wanted to point out your function call:

csv2xml($_POST['file'], $container = 'wholething', $rows = 'item');

Although it works, this is not how you call functions.

csv2xml($_POST['file'], 'wholething', 'item');

Is what you mean to do.

Justin Johnson