Skip to content
Advertisement

Count number of columns in a CSV file, using PHP?

Is it possible to validate a text file before I dump its data into a MYSQL database?

I want to check if it contains, say, 5 columns (of data). If so, then i go ahead with the following query:

JavaScript

If not, I remove the entire row. I repeat this process for all rows in the txt file.

The text file contains data of the format:

JavaScript

Advertisement

Answer

EDIT: After reading your comments, here’s the code for doing the same on tab separated data:

JavaScript

This code reads a file, let’s say “myfile.txt”, line by line, and sets variable $error to true if any of the lines has a length of more than $max_cols. (My apologies if that’s not what you’re asking, your question is not the most clear to me)

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement