reading first 5 fields of csv file in php - php

I am confused on how to read a csv file in php ( only the first 4 fields) and exclude the remaining fileds.
Sno,Name,Ph,Add,PO
1,Bob,0102,Suit22,89
2,Pop,2343,Room2,78
I just want to read first 3 fileds and jump to next data. cannot figure out how to do through fgetcsv
any help?
Thanks,

I added a comment to the sample fgetcsv code for you:
$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";
// iterate over each column here
for ($c=0; $c < $num; $c++) {
// handle column data here
echo $data[$c] . "<br />\n";
// exit the loop after 3rd column parsed
if ($c == 2) break;
}
++$row;
}
fclose($handle);
}

Here's a way to do it without the fgetcsv function:
$lines = file('data.csv');
$linecount = count($lines);
for ($i = 1; $i < $linecount; $i++){
$fields = explode(',', $lines[$i]);
$sno = $fields[0];
$name = $fields[1];
$ph = $fields[2];
$add = $fields[3];
}

Related

Retrieve columns data for each line csv

I want to retrieve for each line all data for a specific column of a csv file.
File structure
Swimlane,Column,ID,Title
For example retrieve all data for the column "Title".
Code:
$row = 1;
if (($handle = fopen("Business Backlog API Publication.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// Column title
$num = $data[4];
echo "<p> $num : $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
Thank you so much
If file is not huge, you can use file() function:
$lines = file("Business Backlog API Publication.csv");
$row = 0;
foreach($lines as $line)
{
$line = explode(",", $line);
$title = $line[3];
echo "<p> $row : $title: <br /></p>\n";
$row++;
}
Note that title is at index 3, not 4

PHP Read from a CSV-file

I have a simple CSV-file which looks like this:
Value:
AAA
Value:
BBB
Value:
AAA
I want to count the number of times a certain value shows up (e.g. AAA).
To start, I want to get the lines which read "Value:" and just echo the following line "line[$i+1] which would be the corresponding value.
Here's the code:
<?php
$file_handle = fopen("rowa.csv", "r");
$i = 0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$line[$i] = $line_of_text[0];
if($line[$i] == "Value:"){
echo $line[$i+1]."<br />";
}
$i++;
}
fclose($file_handle);
?>
The outcome should look like this:
AAA
BBB
AAA
Unfortunately, this doesn't work..It just gives me "<*br /">s
If you are printing on command line or a file, you need to use \n instead of <br/>. That only works if your output is HTML. Also every time you want to move two lines. the logic should look like this:
if($line[$i] == "Value:"){
echo $line[$i+1]."\n"; // add a new line
}
$i+=2; // you want to move two lines
This doesn't look like a normal everyday CSV file, but here's an example that should work.
$fh = fopen('rowa.csv', 'r');
$OUT = array();
$C = 0;
while( ! feof($fh) ) {
// read 1 line, trim new line characters.
$line = trim(fgets($fh, 1024));
// skip empty lines
if ( empty($line) ) continue;
// if it's a value line we increase the counter & skip to next line
if( $line === 'Value:' ) {
$C++;
continue;
}
// append contents to array using the counter as an index
$OUT[$C] = $line;
}
fclose($fh);
var_dump($OUT);
This is not a CSV file. The file() command will load the lines of a file into an array. The for loop prints every second line.
$lines = file("thefile.txt");
for ($i = 1; $i < count($lines); $i = $i + 2) {
echo $lines[$i] . "<br/>" . PHP_EOL;
}
As PHP.net example provides, you can use this modified code:
<?php
$count = 0;
if (($handle = fopen("test.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
for ($c=0; $c < $num; $c++)
{
if (!strcmp($data[$c], 'Value:')) continue;
if (!strcmp($data[$c], 'AAA')) $count++;
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
UPDATE
Try this new code, we use the value as array key and increment the count for that "key".
<?php
$counts = array();
if (($handle = fopen("test.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$num = count($data);
for ($c=0; $c < $num; $c++)
{
if (strcmp($data[$c], 'Value:'))
{
if (!isset($counts[$data[$c]]))
{
$counts[$data[$c]] = 0;
}
$counts[$data[$c]]++;
}
else
{
// Do something
}
}
}
fclose($handle);
}
var_dump($counts);
?>
You can print the array like this:
foreach ($counts as $key => $count)
{
printf('%s: %d<br/>' . "\n", $key, $count);
}

How to transform while loop into foreach loop in the context of using fopen and fgetcsv functions?

This is the standard code on php.net:
<?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);
}
?>
Let's assume that test.csv has 3 rows with:
cell11,cell12,cell13
cell21,cell22,cell23
cell31,cell32,cell33
Is it possible to use a foreach loop instead of the while used here and still get the values inside test.csv, for further use?
The code above gives this result:
3 fields in line 1:
cell11
cell12
cell13
3 fields in line 2:
cell21
cell22
cell23
3 fields in line 3:
cell31
cell32
cell33
This is what I have tried:
<?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";
// }
// }
foreach(($data = fgetcsv($handle, 1000, ",")) as $field){
$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);
}
?>
And the result:
3 fields in line 1:
cell11
cell12
cell13
3 fields in line 2:
cell11
cell12
cell13
3 fields in line 3:
cell11
cell12
cell13
This:
foreach(($data = fgetcsv($handle, 1000, ",")) as $field){ ...
Passes the data from fgetcsv to the new variable $data which doesn't make sense in this case. You can just write this:
foreach (fgetcsv($handle, 1000, ",") as $field) { …
But to explain why foreach doesn't work:
As fget (and thus fgetcsv) is a function it does not work as an array, it just returns one, namely the next line in the file.
The foreach example above just gets the first line from that function and iterates over it. This means you iterate over each column of the first line.

PHP Get values from CSV into an array

I have the following csv file:
9 carat gold,11.87
18 carat gold,23.73
Silver,0.49
Platinum,27.52
I would like to put this in a Multidimensional Array but i have no idea how to.
Thanks for any help.
Try this code
$csv = file_get_contents($file);
$data = explode(PHP_EOL, $csv);
$arr = array();
foreach ($data as $entry) {
$arr[] = str_getcsv($entry);
}
print_r($arr);
You can go through this link for more details about str_getcsv function
You can use fgetcsv to parse a CSV file without having to worry about parsing it yourself.
Example from PHP Manual:
$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);
}
You can use fgetcsv to read a csv file open with fopen.

Read and load two CSV files

I have two very small CSV files that I want to load into array and compare each row and their individual cells, and if there is a change in any cell highlight it.
At the moment I am writing a script to load files and display these onto the browser as they appear on the files.
CSV structure:
My PHP Code:
<?php
$row = 1;
$row2 = 1;
if (($file = fopen("Workbook1.csv", "r")) !== FALSE && ($file2 = fopen("Workbook2.csv", "r")) !== FALSE ) {
while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row Orginal File: <br /></p>\n";
$row++;
for ($i=0; $i < $num; $i++) {
echo $data[$i] . "<br />\n";
}
while(($data2 = fgetcsv($file2, 1000 , ",")) !== FALSE){
$num2 = count($data2);
echo "<p> $num2 fields in line $row2 Updated File: <br /></p>\n";
$row2++;
for ($x=0; $x < $num2; $x++) {
echo $data2[$x] . "<br />\n";
}
}
}
fclose($file);
fclose($file2);
}
?>
Browser Result:
Not to sure why the Array is structured like above image as i understand fgetcsv() read line by line.
Any one can see my my stake in code..?
You are not closing the first while loop in the right place.
Try this
<?php
$row = 1;
$row2 = 1;
if (($file = fopen("Workbook1.csv", "r")) !== FALSE && ($file2 = fopen("Workbook2.csv", "r")) !== FALSE ) {
while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row Orginal File: <br /></p>\n";
$row++;
for ($i=0; $i < $num; $i++) {
echo $data[$i] . "<br />\n";
}
} // end first while loop
while(($data2 = fgetcsv($file2, 1000 , ",")) !== FALSE){
$num2 = count($data2);
echo "<p> $num2 fields in line $row2 Updated File: <br /></p>\n";
$row2++;
for ($x=0; $x < $num2; $x++) {
echo $data2[$x] . "<br />\n";
}
}
fclose($file);
fclose($file2);
}
?>
After reading this enter link description here
I managed to fix it by adding this line of code at the top of the file before fopen()
ini_set('auto_detect_line_endings',TRUE);
If you need to set auto_detect_line_endings to deal with Mac line
endings, it may seem obvious but remember it should be set before
fopen, not after:
Having this fixers how can i Compare the values between these two files..?

Categories