fgetcsv将数组转换为带双引号机箱的字符串

时间:2017-02-24 10:53:43

标签: php arrays csv fgetcsv

我使用fgetcsv函数从csv获取数据作为数组。我想将数组转换为字符串,所以我使用了implode函数。

CODE:

if (($handle = fopen("storelocations.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $datafinal = implode(",",$data);
        echo $datafinal;
    }
    fclose($handle);
}

我得到的结果字符串为Ter Aar, Netherlands,4.7159509,52.164688,,211316 但我希望每个条目都用双引号括起来。我该怎么办?

预期结果:`" Ter Aar","荷兰"," 4.7159509"," 52.164688"," "" 211316"

我的方法#1 -

我在documentation之后通过"作为附件,但它无效。

if (($handle = fopen("../storelocations.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",", '"')) !== FALSE) {
        $datafinal = implode(",",$data);
        echo $datafinal;
    }
    fclose($handle);
}

我的方法#2 -

function convert( $str ) {
   return '"'.$str.'"';
}

if (($handle = fopen("../storelocations.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",", '"')) !== FALSE) {
        //$datafinal = array_map( convert, $data );  
        $datafinal = implode(",",$data);
        echo $datafinal;
        //var_dump($data);
    }
    fclose($handle);
}

这会返回一个字符串"Ter Aar", "Netherlands","4.7159509","52.164688","","""211316"

正如您所看到的,空白数据后面的项目在开头有三个引号。

2 个答案:

答案 0 :(得分:2)

您可以按照以下方式执行此操作

// PHP 5.3 and later
echo $datafinal = implode(",",array_filter($data, function($value) { return $value !== ''; })); 

这有助于您确定

由于 希望!它会帮助你

答案 1 :(得分:1)

尝试使用以下代码来读取csv文件并将数据作为多维数组

$csv_data = array_map('str_getcsv', file('../storelocations.csv'));
foreach ($csv_data as $key => $value) 
{
    var_dump($value); // print each row of csv
    var_dump($value[0]) // print first column of each row
}