4

Possible Duplicate:
Load and read a csv file with php

I have the following string:

Mr,Tom,Jones,Add1,Add2,"Add3,Add3 extra",Town,County,postcode,99999,888,777

I am tring to get the string into an array that looks like the below:

Array
(
    [0] => Mr
    [1] => Tom
    [2] => Jones
    [3] => Add1
    [4] => Add2
    [5] => "Add3,Add3 extra"
    [6] => Town
    [7] => County
    [8] => Postcode
    [9] => 99999
    [10] => 888
    [11] => 777
)

if you explode the string by "," it splits array item 5 into 2 parts which I am trying to avoid. The original data comes from a CSV.

Ultimatly I am trying to import a CSV and create a new DB on the fly with the headers and file content against the correct headers.

Thanks in advance.

Community
  • 1
  • 1
makie
  • 41
  • 1

4 Answers4

6

Try fgetcsv():

fgetcsv — Gets line from file pointer and parse for CSV fields

kapa
  • 77,694
  • 21
  • 158
  • 175
Peter Kiss
  • 9,309
  • 2
  • 23
  • 38
2
$array = str_getcsv( 'Mr,Tom,Jones,Add1,Add2,"Add3,Add3 extra",Town,County,postcode,99999,888,777', ',', '"' );

This will get you to an array with what you want.

str_getcsv()

kapa
  • 77,694
  • 21
  • 158
  • 175
Jester
  • 1,285
  • 14
  • 24
0
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

From fgetcsv

cybertextron
  • 10,547
  • 28
  • 104
  • 208
0

You can use str_getcsv().

str_getcsv — Parse a CSV string into an array

Shubham
  • 21,300
  • 18
  • 66
  • 89