简体   繁体   中英

comma problems while reading CSV file with fgetcsv

I have a CSV file that I am trying to read but some of the field values contain commas and it is throwing off my code. I am using fgetcsv to read the file.

sample of csv file i am reading from

"Stock Number","product","title","size","description","price"
"195642","T-Shirt","100% cotton classic fit","XL","Cotton shirts breathe better than clothing made with synthetic materials, and are less prone to retaining odors and losing shape.We offer a wide variety of cotton t-shirts from leading brands such as Fruit of the Loom, Hanes, New Balance, and more.","6.99"

The problem is that the values in the description field contain commas.

// open file
$txtfile = fopen('../folder/where/file.csv', 'r');

// skip first line (header)
fgetcsv($txtfile, 10000, ",");
while (($line = fgetcsv($txtfile)) !== FALSE) {
}
// close file
fclose($txtfile);

In the while loop, I am writing all the information from this CSV file to a larger CSV which get inserted into a database.

The issue I am having is my array gets thrown off by the commas in the description field. For example, this is one of the descriptions

"Cotton shirts breathe better than clothing made with synthetic materials, and are less prone to retaining odors and losing shape.We offer a wide variety of cotton t-shirts from leading brands such as Fruit of the Loom, Hanes, New Balance, and more."

When my codes reads the file and I try to ouput the value for $line[4] i get

Cotton shirts breathe better than clothing made with synthetic materials

and then $line[5] which should be price outputs

and are less prone to retaining odors and losing shape.We offer a wide variety of cotton t-shirts from leading brands such as Fruit of the Loom

Try specifying the enclosure character. I couldn't see anything in the manual that says there's a default enclosure:

fgetcsv($txtfile, 10000, ",", '"');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM