2016-03-05 125 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,

相关问题