我知道有很多资源可以将CSV放入关联数组,但我找不到任何东西可以帮助像我这样的人做我想做的事情。
我目前在我的PHP文件中定义了一个关联数组:
$users = array(
'v4f25' => 'Stan Parker',
'ntl35' => 'John Smith',
);
我想把这个数组移到CSV文件(users.txt(中,所以:
v4f25, Stan Parker
ntl35, John Smith
下一步是导入users.txt,这样我就可以像使用数组$users一样使用它。
这里有人帮忙吗?我尝试的最后一个代码返回了这个:(这不是我想要的(
array(2) {
["v4f25"]=>
string(5) "ntl35"
["Stan Parker"]=>
string(10) "John Smith"
}
以下内容如何?
$data = array();
if ($fp = fopen('csvfile.csv', 'r')) {
while (!feof($fp)) {
$row = fgetcsv($fp);
$data[$row[0]] = $row[1];
}
fclose($fp);
}
$users = array(
'v4f25' => 'Stan Parker',
'ntl35' => 'John Smith',
);
$fp = fopen('users.txt', 'w');
if ($fp) {
foreach ($users as $key => $value) {
fputcsv($fp, array($key, $value));
}
fclose($fp);
} else {
exit('Could not open CSV file')
}
参见:fputcsv()
UPDATE-在评论中,您对如何读取文件和让用户退出感兴趣。这是回程:
$users = array();
if (($handle = fopen("my-csv-file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$users[$data[0]] = $data[1];
}
fclose($handle);
} else {
exit('Could not open CSV file');
}
if (count($users) == 0) {
exit('CSV file empty: no users found');
}
这里有一个使用fputcsv()
的解决方案,它在写入磁盘之前将键/值对展平为数组。
$filehandle = fopen("csvfile.csv", "w");
if ($filehandle) {
foreach ($users as $key => $value) {
fputcsv($filehandle, array($key, $value);
}
fclose($filehandle);
}
else // couldn't open file
试试这个(假设你的字符串不包含逗号(:
$users = array(
'v4f25' => 'Stan Parker',
'ntl35' => 'John Smith',
);
foreach ($users as $k => $v) {
print "$k, $v'n";
}
显然,您可以创建CSV文件,如下所示:
php above_script.php > outfile.csv
现在,要从CSV返回到数组中,您可以使用以下内容:
$file = 'outfile.csv';
$arr = array();
if (file_exists($file)) {
foreach (explode("'n", file_get_contents($file)) as $l) {
list($k, $v) = explode(',', $l);
$arr[trim($k)] = trim($l);
}
}
print_r($arr, true);
注意:
如果您的字符串do(或者可能(包含逗号,那么您可能需要使用PHP内置函数来解码它们——在这种情况下,harald和artlung的答案很有用。
RFC 4180描述了逗号(和其他值(如何在CSV中编码,以防您出于任何原因想要滚动自己的CSV编码/解码功能。