I need to print out csv file into html or put a numeric data into database:
But I need to start a loop at specific position and break it at another specific position (regex).
So I need to reprint only rows with numerical data and all columns from them.
Following is pseudo-code - not working properly:
<?php
$row = 1;
$handle = fopen("test.csv", "r");
while ($data = fgetcsv($handle, 1000, ","))
{
if (preg_match('/[Morning]/', $data[0]) === 1 // start at this rwo plus two lines down )
{
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++)
{
for ($c=0; $c < $num; $c++)
{
echo $data[$c] . " ";
}
if (preg_match('/[Total Cash:]/', $data[0]) === 1)
{ break; row -1 }
}
echo "<br>";
}
}
fclose($handle); ?>
So csv goes like this:
/--some lines--/
Date: 3/3/11,
Morning,
--blank line---
Customer No,Time,CheckNo,Total,
1234,12-45,01,20.00,
1236,1-00,03,30.00,
1240,2-00,06,30.00,
--more numerical rows of data at variable length that I need to loop over--
1500,4-00,07,22.00,
----,----,---,----,
Total Cash, , , ,120.00,
/--some other lines--and it goes/
Lunch Time,
---similar like Morning above ---
Any info how to properly addrres this issue is appreciated, I can now do so many loops and regex but with this I need some more time and help. Thanks.
$lines = file('test.csv'); //read file into an array, one entry per line
$active = false; //keep track of what rows to parse
//loop one line at a time
for ($i = 0; $i < count($lines); $i++) {
$line = $lines[$i];
if (strpos($line, 'Morning') !== false) { //start parsing on the next row
$active = true;
$i += 2; //skip the blank line and header
continue;
}
if (strpos($line, '----,') !== false) { //stop parsing rows
$active = false;
}
if ($active) { //if parsing enabled, split the line on commas and do something with the values
$values = str_getcsv(trim($line));
foreach ($values as $value) {
echo $value . " "; //these are the numbers
}
}
}
$lines = file('test.csv');
$parsing = false;
foreach ($lines as $line)
{
$parsing = ((strpos($line, 'Morning') !== false) || $parsing)
&& ((strpos($line, 'Total Cash') === false);
if (!$parsing)
continue;
$values = strgetcsv($line);
echo implode(' ', $values);
}
Edit: Basically, it does the same as Dan Grossmans solution, but shorter ;-)
$lines = file('test.csv');
// Skip the unwanted lines
// Means: Every line until the line containing "Morning,"
do {
$line = array_shift($lines);
} while(trim($line) !== 'Morning,');
$lines = array_slice($lines, 2); // Mentioned something about "2 lines below" or such" ^^
// Do something with the remaining lines, until
// Line _begins_ with "Total Cash"
while(strncmp('Total Cash', trim($line = array_shift($lines)), 10) !== 0) {
echo implode(' ', str_getcsv($line)) . PHP_EOL;
}
Related
I have a CSV file with 100 rows but want to output 5 of them at random like $data[0][1][2][3] and $data[2][2][3]
I got it to show but it shows in a group
<?php
$row = 1;
if (($handle = fopen("Book1.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
Would like it to look like:
some data:<?php echo $data[0][1][2][3];?>
more data:<?php echo $data[1][1][2][3];?>
more data:<?php echo $data[5][1][2][3];?>
more data:<?php echo $data[8][1][2][3];?>
If you load the file into an array, it's easy enough to come up with a list of "random" numbers, pull the corresponding line out, and use str_getcsv the same way you used fgetcsv in your code. It isn't the most efficient way to do it, as you need to read the whole file into memory. But it's necessary to determine the number of lines before choosing your random number.
<?php
$rows = file("Book1.csv");
$len = count($rows);
$rand = [];
while (count($rand) < 5) {
$r = rand(0, $len);
if (!in_array($r, $rand)) {
$rand[] = $r;
}
}
foreach ($rand as $r) {
$csv = $rows[$r];
$data = str_getcsv($csv);
// now do whatever you want with $data, which is one random row of your CSV
echo "first column from row $r: $data[0]\n";
}
How to skip first row and read upto five rows from csv in PHP
Hello,
I have following code in which I want to skip first row in csv that is headers of columns and read upto five rows of csv file.
Current code skip first row but display all records.
How can I achieve this ?
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
set_time_limit(0);
define('CSV_PATH', '/var/www/Products_upload_12499/'); // specify CSV file path
$csv_file = CSV_PATH . "skipfirstrow.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$counter = 1;
while ($data = fgetcsv($csvfile))
{
if($counter==1) {
$counter++;
continue;
} }
$days = trim($data[0]);
echo "==>> " . $days."\n";
if ($counter >= 6) {
exit();
}
}
?>
You can create an if else conditional that only outputs the rows you want, and that breaks the while loop when you got all the rows you wanted:
$row = 0;
while ($data = fgetcsv($csvfile))
{
$row++;//starts off with $row = 1
if (($row>1)&&($row<6))//rows 2,3,4,5
{
foreach ($data as $cell)
{
echo "| {$cell} |";
}
echo "<br>";
}
else if ($row>=6)
{
break;
}
}
You can replace the echo "| {$cell} |"; code with whatever you like the code to output.
Let me know if this worked for you.
Yet another code to achieve this.
fgets used to skip lines to avoid excess csv parsing.
if (($f = fopen('test.csv', 'r')) === false)
throw new Exception('File not found');
$skip = 1;
$length = 5;
for ($i = 1; $i < $skip; $i++) fgets($f); // skip first $skip lines
for ($i = $skip; $i < $skip + $length; $i++) {
$row = fgetcsv($f);
echo implode(', ', $row)."<br/>\n";
}
just skip first line by not equal assign != ,let me know is it work
$counter = 1;
while ($data = fgetcsv($csvfile))
{
if($counter !=1) {
$days = trim($data[0]);
echo "==>> " . $days."\n";
if($counter >= 6)
break;
}
$counter++;
}
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);
}
I have text file
name,name1
willhaveishere1
name,name2
willhaveishere2
name,name3
willhaveishere3
i want read it and return like that
$nn = name1
$ss = willhaveishere1
with my code i get only name1
my code is
$file1 = "file.txt";
$file = file($file1);
$count = count($file);
if($count > 0) {
$i = 1;
foreach($file as $row) {
$n = strstr($row, 'name,');
$cc = array("name,");
$dd = array("");
$nn = str_replace($cc, $dd, $n);
echo $nn;
$i++; } }
This is probably what you need
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
echo substr($row, $pos + 1);
$nn[] = substr($row, $pos + 1);
} else {
echo $row;
$ss[] = $row;
}
}
}
EDIT
Yes, just loop through, but make sure both $nn and $ss has same count, which is depending on your file.
Also Note: mysql_* functions has been deprecated, so please use mysqli or PDO instead
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]')"; mysql_query($sql);
}
EDIT 2
try this example:
$file = array(
0 => 'name,name1',
1 => 'willhaveishere1',
2 => 'name,name2',
3 => 'willhaveishere2',
4 => 'name,name3',
5 => 'willhaveishere3'
);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$nn[] = substr($row, $pos + 1);
} else {
$ss[] = $row;
}
}
}
echo '<pre>';
$count = count($nn);
for($i=0; $i < $count; $i++){
$sql = "INSERT INTO users(name, line) VALUES('$nn[$i]', '$ss[$i]');";
echo $sql.PHP_EOL;
}
You can try this straightforward method:
if($fh = fopen("file.txt","r")){
$nameBefore = false;
//loop through every line of your file
while (!feof($fh)){
$line = fgets($fh);
//check if the name was detected in previous line
if ($nameBefore !== false)
{
//you have the set of name and line, do what you want
echo $nameBefore . ': ' . $line . '<br />';
$nameBefore = false;
}
else
{
//see if the line is made of two coma separated segments and the first one is 'name'
//Remember the name for the next line
$parts = explode(',', $line);
if (count($parts) == 2 && $parts[0] == 'name')
$nameBefore = $parts[1];
}
}
fclose($fh);
}
One option is to use strpos to find the first occurrence of the character in the line, and if found remove everything from the line before that position. This way you are left with only the part of the line you are interested in.
Code:
$character = ',';
$fileHandle = fopen('file.txt', 'r');
while (!feof($fileHandle)) {
// Retrieve the line from the file
$line = fgets($fileHandle);
// If the line contains the character
// Remove everything before the character
$charPos = strpos($line, $character);
if ($charPos !== false) {
$line = substr($line, $charPos + 1);
}
// Do something with the remainder of the line
echo $line . PHP_EOL;
}
fclose($fileHandle);
Output:
name1
willhaveishere1
name2
willhaveishere2
name3
willhaveishere3
If you wish to retrieve the following line, simply do another retrieve line call in your loop:
while (!feof($fileHandle)) {
// Retrieve two lines in one loop iteration
$lineOne = fgets($fileHandle);
$lineTwo = fgets($fileHandle);
}
Making sure to only apply the comma replace part on the first line. This can lead to problems though if your data is... inconsistent.
Hope this helps.
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];
}