php read CSV with various amount of delimiters - php

I've got a script that reads in from a CSV file and sometimes the CSV files it receives contains an uneven amount of delimiters/columns so the first row could have 30 columns, the 2nd could have 20, etc. I can think of a few solutions myself ie:
Count the delimiters in the widest row, then append the proper amount to each row that is short to make them even.
But I was wondering if anyone had a more elegant method of doing this.

It depends on what you are using to read the CSV the most elegant have seen is fgetcsv Please see http://www.php.net/manual/en/function.fgetcsv.php for more information
There is an example there that counts number of CSV:
$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);
}

Related

How to skip the n first lines with PHP function fgetcsv() or fopen()?

After opening CSV files with fopen(), I'm currently skipping the three first lines of these files like this:
fgetcsv($file, 0, ';');
fgetcsv($file, 0, ';');
fgetcsv($file, 0, ';');
Is there a nicer method to skip the n first lines ?
If you need to skip more than a handful of lines, simply add one instance of the "throw-away read" code you already have inside a for loop. Number of loops equals lines skipped (e.g. 8 lines):
for ($i = 0; $i < 8; $i++) {
fgetcsv($file, 0, ';');
}
Do this before you begin your main while loop getting the CSV lines you care about. You could turn the loop into a utility function -- if you find yourself doing this often at different skip lengths.
function fskipcsv_lines($handle, int $lines) {
for ($i = 0; $i < $lines; $i++) {
fgetcsv($handle, 0, ';');
}
}
Simple enough. Same construct applies for the "dumb" repetition of any other function you don't need to get a a return value from, that simply needs to be called N times.
P.S. Don't place the "skip line" check routine inside your main CSV iteration loop. Why? Because the check (e.g. $row < 3; or in_array($row, $skips)) would happen at each loop iteration. Suppose you need to read 100,000+ lines, the overhead will start adding up, unnecessarily burdening each loop iteration for the first (now past) few lines' sake.
Your are doing right, but this code may help if you are going to skip many. :
$skippTheseLines = array(1,2,3);
$i = 0;
$totlLines= 10000;
while (($emapData = fgetcsv($file, $totalLines, ";")) !== FALSE) {
if(in_array($i, $skippTheseLines)) {
continue;
}else{
// rest of your code
}
$i = $i + 1;
}
Check out this code. Similar questions: skip first line of fgetcsv method in php
$file = fopen('example.csv', 'r'); // Here example is a CSV name
$row = 1;
$number_to_skip = 3
while (($line = fgetcsv($file,0, ",")) !== FALSE) {
// $line is an array of the csv elements
if($row < $number_to_skip)
{
$row++; continue; // continue is used for skip row 0,1,2
}
print_r($line);
}

parse CSV file in PHP by column

I want to open CSV (comma separated value) file in PHP by column, i want to take all datas from 3 columns. I tried with this code, but this only shows me data by row:
$row = 1;
if (($handle = fopen("ut.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);
}
How i can take all datas from one column ?
EXAMPLE:
This i my file in Excel, which is exported to SCV:
http://prntscr.com/mzcfcw
I want to take in php values from colum Name and Price and find duplicate values in column Name, compare their prices.
fgetcsv parses the given handle line by line (rows). It isn't possible to parse a csv file by column using core php. However, if you know the position of the 3 columns for which you wish to access the values, you could simply ignore all other columns:
//position (zero indexed) of required columns
$columnsToProcess=[0,3,4]
for ($c=0; $c < $num; $c++) {
//do something with value if column's index is in the required columns array
if(in_array($c,$columnsToProcess)){
//value at position $c equals $data[$c]
echo $data[$c] . "<br />\n";
}
}
Moe info about fgetcsv : http://php.net/manual/en/function.fgetcsv.php

How to load the values from Excel to a table using PHP

Is there any way to load the values from MS Excel to a database table using PHP?
If you still want to load XLS directly from PHP it's possible .
`http://sourceforge.net/projects/phpexcelreader/
You could also save excel files in .csv format and take a look at this: http://php.net/manual/en/function.fgetcsv.php
<?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);
}
?>
The example I provided opens the file and echos the content of the file.
Live example
The contents of the live example:
5 7 12
6 8 14
7 9 16
8 48 56
9 8 17
10 4 14
Third line is =A1+B1, =A2+B2 and so on...

PHP Displaying multiple lines with fgetcsv

I'm using a CSV file to enter various things such as image filenames or descriptions to pull into variables for my site.
if (($handle = fopen("properties/properties.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$row++;
$num = count($data);
${'property'.$row.'mainimg'} = '"'."properties/".$data[0].'"';
${'property'.$row.'col1desc'} = $data[1];
for ($c=0; $c < $num; $c++) {
}
}
fclose($handle);
}
I'm using Excel 2010 to edit the .csv. When I put in text like this into a cell:
line 1
line 2
line 3
it's saved into the .csv like this (copy paste from notepad):
"line 1
line 2
line 3"
and comes out like this on my page:
line 1 line 2 line 3
What can I do to display these multiple lines from a single cell in the .csv?
Thanks!
Do not use fgetcsv. Csv is designed to take line break as different row, and your attempt using it with new line character in a field will go nowhere.
Try file_get_contents first, explode with "\"\n\"" (line break enclosed by quoteation mark) then explode with "," again.

Trouble understanding a PHP code sample

I've been looking around to see if anyone else has dissected this code already, but that has proven to be futile. I'm having some trouble understanding what's happening in this php code sample from here.
I'm still currently very new to programming and PHP as a whole so I'm hoping someone can give me a clean explanation (I have read the documentation, but I still fail to fully understand the code)
I'm currently tackling on a project to convert an uploaded CSV file into an array and then into a database. The sample code is below:
Example #1 Read and print the entire contents of a CSV file
<?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);
}
?>
I guess my problem really is with understanding the fgetcsv method, but if someone could provide me with a breakdown it would really be appreciated.
$row = 1;
Sets the initial number of rows processed.
if (($handle = fopen("test.csv", "r")) !== FALSE) {
Attempts to open the file (for reading only), continuing only if it can.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
Iterates over each line in the CSV (with a maximum length of the row being 1,000 characters and the field delimiter being a comma), continuing only if it can, pulling the row out as an indexed array of the fields.
$num = count($data);
Gets the number of fields in the row.
echo "<p> $num fields in line $row: <br /></p>\n";
Outputs the number of fields in the given row.
$row++;
Increments the row number.
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
Iterates over each field in the row and outputs its value.
fclose($handle);
Closes the file.
fgetcsv reads your csv row-by-row.
It return ana associative array. If you have 10 columns in the csv for example:
csv1,csv2,csv3,...csv10 the $data variable each cycle will be an array like (csv1 => "value"1 ... csv10->"value10")
So your code print first the num of columns of the csv file
count($data)
then iterate the row taken from csv and print all the columns values
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
This is done for each row of the file

Categories