Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

php - Converting CSV to array

I have this array with airport codes and city names (around 3500 lines).

code,city
"Abilene, TX ",ABI
"Adak Island, AK ",ADK
"Akiachak, AK ",KKI
"Akiak, AK ",AKI
"Akron/Canton, OH ",CAK
"Akuton, AK ",KQA
"Alakanuk, AK ",AUK
"Alamogordo, NM ",ALM

I need to convert that file into a php array. This is my code so far:

if(($handle = fopen('test.csv', 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ',', '"')) !== FALSE) {
        echo '<pre>';
            print_r($data);
            echo '</pre>';
    }
    fclose($handle);
}

Although I'm setting the delimiter and enclousure characters for the fgetcsv function, im getting this as a result:

Array
(
    [0] => code
    [1] => city
"Abilene
    [2] => TX "
    [3] => ABI
"Adak Island
    [4] => AK "
    [5] => ADK
"Akiachak
    [6] => AK "
    [7] => KKI
"Akiak
    [8] => AK "
    [9] => AKI
"Akron/Canton
    [10] => OH "
    [11] => CAK
"Akuton
    [12] => AK "
    [13] => KQA
"Alakanuk
    [14] => AK "
    [15] => AUK
"Alamogordo
    [16] => NM "
    [17] => ALM
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If it's the linebreaks, you can try the brute-force method with:

$file = file_get_contents("test.csv");
$data = array_map("str_getcsv", preg_split('/
*
+|
+/', $file));
print_r($data);

str_getcsv is available with PHP 5.3, or as workaround in the manual, via upgradephp or PHP_Compat.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...