2009-09-30 42 views
0

我需要上傳一個文件(在這種情況下,CSV文件)處理,並加載它的內容分爲以下幾個功能:通過表單提交文件,並在一個PHP函數

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

這是怎麼IM調用函數

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

在表單中輸入框的名稱是文件

我得到以下警告:

fgetcsv() expects parameter 1 to be resource, null given 

回答

2

您需要首先打開文件,如:

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

然後使用:

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

檢索您的數據。

請注意,您可能需要查看PHP的file upload信息,以確保您使用$ _FILES數組獲取您上傳的文件。而不僅僅是$ _POST。

0

@richsage已經回答了這個問題。如果你仍然有問題,visit the documentation作爲一個工作的例子。我只是想指出你的函數調用:

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

雖然它的工作,這不是你如何調用函數。

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

是你的意思。