2016-03-05 44 views
2

我正在使用WordPress的高級自定義字段插件來允許用戶上傳CSV文件。然後我需要從該CSV文件中獲取數據。我知道我需要使用fgetcsv()php函數,但是我遇到了麻煩。從高級自定義字段的'文件'字段解析CSV文件

我可以打印對象是這樣的:

$file = get_field('location_info'); 
print_r($file); 

這給了我

Array ([id] => 8 [alt] => [title] => locations [caption] => [description] => [mime_type] => text/csv [url] => http://lc.something.com/wp-content/uploads/2016/03/locations.csv) 

所以,我怎麼能得到的數據出來使用PHP是csv文件中。

我目前正在:

$file = get_field('location_info'); 
$filecontents = fgetcsv($file); 

但是,這給我的錯誤「

Warning: fgetcsv() expects parameter 1 to be resource, array given in /var/www/websites/metromont/app/wp-content/themes/metromont/page-contact.php on line 7" 

我如何得到 '資源' 出這種

+0

[fgetcsv ](http://php.net/manual/en/function.fgetcsv.php)需要一個資源。你可以嘗試使用'url'像這樣'$ file = get_field('location_info')['url'];' –

+0

試過但得到相同的錯誤信息。 – JordanBarber

+0

你不應該得到相同的錯誤信息,因爲添加'['url']'會拉到一個字符串值 - 你能更新你的代碼和錯誤信息嗎? –

回答

0

Fgetcsv()功能?希望這個資源:

處理

有效文件指針由fopen()popen(),或者fsockopen()成功打開的文件。

嘗試使用下面讓CSV內容的代碼片段:

$file = get_field('location_info'); 

if ($file) { 
    if (($handle = fopen($file["url"], "r")) !== FALSE) { 
    while (($data_row = fgetcsv($handle, 1000, ",")) !== FALSE) { 
     $num = count($data_row); 
     for ($c=0; $c < $num; $c++) { 
     echo $data_row[ $c ] . ", "; 
     } 
     echo "<br />"; 
    } 
    fclose($handle); 
    } 
} 

輸出採樣數據:

ID,名字,姓氏,電子郵件地址,性別,IP_ADDRESS

1,Philip,Evans,[email protected],男,8.106.111.3,

2,雷蒙德,馬修斯,[email protected],男性,165.36.29.127,

3,凱西,勞倫斯,[email protected],女,17.23.224.247,

相關問題