I want to read .csv file in PHP and put its contents into the database. I wrote the following code:
$row = 1;
$file = fopen("qryWebsite.csv", "r");
while (($data = fgetcsv($file, 8000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "\n";}}
fclose($file);
I do not get any error but it does not show me result.
Try this....
In PHP it is often useful to be able to read a CSV file and access it’s data. That is where the fgetcsv() function comes in handy, it will read each line of a CSV file and assign each value into an ARRAY. You can define the separator in the function as well see PHP docs for fgetcsv() for more options and examples.
I am using parseCSV class to read data from csv files. It can give more flexibility in reading csv file.
One liner to parse a CSV file into an array by using str_getcsv.
To build a database query that will import all the values into database at once:
This will build a prepared statement with question mark placeholders, like:
, and variable
$values
will be one-dimensional array that holds values for the statement. One caveat here is that csv file should contain less than 65,536 entries ( maximum number of placeholders ).More Details
this is not tested... but something like this should do the trick:
If you're using the composer package manager, you can also rely on
league/csv
According to theire documentation: