4
"AMZN","Amazon.com, Inc.",211.22,"11/9/2011","4:00pm","-6.77 - -3.11%",4673052

Amazon.com, Inc. is being treated as 2 values instead of one.

I tried this $data = explode( ',', $s);

How do I modify this to avoid the comma in the value issue?

ScottMcGready
  • 1,612
  • 2
  • 24
  • 33
ThinkCode
  • 7,841
  • 21
  • 73
  • 92
  • 4
    You may be looking for http://www.php.net/manual/en/function.str-getcsv.php (However, that's PHP >= 5.3 only) – Pekka Nov 09 '11 at 23:14
  • @Pekka : In the output when I split the returned values and print each value in a separate line. – ThinkCode Nov 09 '11 at 23:17
  • @Galled : Not all values are wrapped in quotes. For instance : 211.22 is not wrapped in quotes. – ThinkCode Nov 09 '11 at 23:19
  • @ScottMcGready Please don't just fix one thing in a post when editing. Fix *everything* (grammar, formatting, tags, etc). – hichris123 Apr 14 '14 at 02:28
  • @hichris123 got a small bit of time to kill and don't want to get too bogged down. Figured I'd do a *little* bit of clean up while I was waiting but fair enough – ScottMcGready Apr 14 '14 at 02:29

2 Answers2

8

You should probably look into str_getcsv() (or fgetcsv() if you're loading the CSV from a file)

This will read the CSV contents into an array without the need for exploding etc.

Edit- to expand upon the point made by Pekka, if you're using PHP < 5.3 str_getcsv() won't work but there's an interesting approach here which reproduces the functionality for lesser versions. And another approach here which uses fgetcsv() after creating a temporary file.

Ben Swinburne
  • 25,669
  • 10
  • 69
  • 108
0

Use a dedicated CSV library. It's been explained over and over that parsing file formats like CSV manually is asking for trouble, because you don't know all the variations of CSV and all the rules to do it right.

erjiang
  • 44,417
  • 10
  • 64
  • 100