douniwan_0025
douniwan_0025
2012-06-11 09:19

来自csv的键值数组,在电子表格中只有两列

已采纳

I have a csv, generated with Open Office Spreadsheet, separator is comma, text wrapper is ".

I want just to columns in my spreadsheet, as it is some key-value list, like:

a -> b
aa -> bb
aaa -> bbb

so my spreadsheet has just two columns, each row containing a key-value pair, each key in a cell, each value in a cell. But when I use

if ($_FILES ['userfile'] ['error'] == UPLOAD_ERR_OK &&
    is_uploaded_file ( $_FILES ['userfile'] ['tmp_name'] )) {

        $csvfile = file_get_contents ( $_FILES ['userfile'] ['tmp_name'] );
    }

    $dict = str_getcsv($csvfile);

And var_dump $dict afterwards, i get

array(4) { [0]=> string(1) "a" [1]=> string(6) "b "aa"" [2]=> 
            string(8) "bb "aaa"" [3]=> string(3) "bbb" }

See index 1, where the first value "b" and the seconde key "aa" are stored in one index.

OpenOffice places no comma behind the values, aka before a new row. How do I avoid that two strings end up in one index? Can I somehow tell str_getcsv that when two " follow each other, it's also a separator? Or can I add a third column always containing # and say "if it contains #, its a line break? (I tried, and couldn't manage..) Or is there even a function, that expects key, value, linebreak in csv?

Whats the correct way to do this? I'm sure people done this so often, but I don't know how to google it.

Thanks!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douxiangui5011 douxiangui5011 9年前

    How about using fgetcsv() ? http://www.php.net/manual/en/function.fgetcsv.php

    It reads line by line, there's an example in the link.

    点赞 评论 复制链接分享