I'm trying to post 3 arrays using foreach and for some reason the break at the end isn't working and it outputs the whole list (40+) on to the page.
$file = fopen('names.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
shuffle($line);
$i = 0;
foreach ($line as $number) {
{
if($i==3){ break; } else {
$rtime = mt_rand(1, 7);
echo $number; }
$i++;
}
}
}
fclose($file);
This is kind of how it looks: take.ms/cLgIh, instead it should only show 3 of these usernames.
<?php
$i = 0;
//I have opened my contact.csv :P
$file = fopen('contact.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
shuffle($line);
foreach ($line as $number) {
{
if($i==3){ exit(); } else {
$rtime = mt_rand(1, 7);
echo "<br/> i = ".$i.$number.", "; }
}
$i++;
}
}
fclose($file);
?>
I have downloade first sample CSV from here:-http://www.sample-videos.com/download-sample-csv.php
And this code works for me:-
<?php
$file = fopen('SampleCSVFile_2kb.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
shuffle($line);
$i = 0;
foreach ($line as $number) {
if($i==3){
exit;
} else {
$rtime = mt_rand(1, 7);
echo $number.'<br/>';
echo $i.'<br/>'; // you can remove this line
}
$i++;
}
}
fclose($file);
?>
Output on each page refresh:-
http://prntscr.com/cln2ju
http://prntscr.com/cln2nf
Note:- if still not work then check your CSV file. May be it is corrupted.
Conclusion:- And after all discussion it comes to an end that your CSV file is corrupted. But yes code improvement is needed too
You need to increment $i otherwise it's value will always be 0
$i = 0;
foreach ($line as $number) {
$rtime = mt_rand(1, 7);
echo "$number";
if($i==3) break;
$i++;
}
Also you need to check if your while statement is closing
$file = fopen('names.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
shuffle($line);
$i = 0;
foreach ($line as $number) {
$rtime = mt_rand(1, 7);
echo $number;
if($i==3) break;
$i++;
}
} //check for this
As I can see in your code example it is missing the closing brace
Also, remove the double quotes from your $number, it's not necessary.
echo $number
You have a mistake is that the break are in the if($i==3) and you declared $i =0, but never increment this. So $i never arrive at 3.
Related
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);
}
When I run the code it is ridiculously slow even if I comment out the second half where I fopen the same file. I have changed the length of stream_get_line. File is 64MB, 73500 lines, 159 columns. Any help to optimize would be much appreciated.
<?php
include "configure.php";
$row = 1;
if(($handle = fopen("ACC_half.txt", "r")) !== false)
{
global $arraySamples;
global $arrayTrans;
global $num;
global $lines;
while (!feof($handle))
{
$data = stream_get_line($handle, 1000000, "\n");
$num = count($data);
$lines = count(file("ACC_half.txt"));
//Get all the names of the samples into array
if($row == 1)
{
for($i=0;$i<$num;$i++)
{
//echo $data[$i];
$arraySamples[]=$data[$i];
}
//Get all the names of the first row(headers) into array for use
}
else
{
$arrayTrans[]=$data[0];
}
$row++;
}
}
fclose($handle);
$row = 1;
$transInc=1;
if(($handle1 = fopen("ACC_half.txt", "r")) !== false)
{
while (($data2 = stream_get_line($handle,1000000,"\n\r")) !== false)
{
if(($row == 2) || ($row==1))
{
$row++;continue;
}
$jnum=count($data2);
for($j=1;$j<$jnum;$j+=2)
{
$g=$j+1;
$h=$j+2;
$import = mysql_query("INSERT into acc (form,sample,raw,scale)
VALUES ('$arrayTrans[$transInc]', '$arraySamples[$g]', '$data2[$j]', '$data2[$g]')")
or die (mysql_error());
}
$transInc++;
}
}
fclose($handle1);
?>
I believe that one of the main problems is that you open the same big file twice. You should open this file once not twice
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;
}
I'm not sure if this is possible, I've been googling for a solution... But, essentially, I have a very large file, the lines of which I want to store in an array. Thus, I'm using file(), but is there a way to do that in batches? So that every,say, 100 lines it creates, it "pauses"?
I think there's likely to be something I can do with a foreach loop or something, but I'm not sure that I'm thinking about it the right way...
Like
$i=0;
$j=0;
$throttle=100;
foreach($files as $k => $v) {
if($i < $j+$throttle && $i > $j) {
$lines[] = file($v);
//Do some other stuff, like importing into a db
}
$i++;
$j++;
}
But, I think that won't really work because $i & $j will always be equal... Anyway, feeling muddled... Can someone help me think a lil' clearer?
Read the file in line by line for however many lines you need, appending each line to an array. When the array gets to the desired length, process it, and empty the array. E.g.:
$handle = #fopen("/tmp/inputfile.txt", "r");
$throttle = 100;
$data = array();
if ($handle) {
while(!feof($handle)) {
$buffer = fgets($handle, 4096);
$data[] = $buffer;
if(count($data) == $throttle) {
doSomething($data);
$data = array();
}
}
fclose($handle);
}
You never incremented $i or $j... What you can do, is something like:
$data = array();
$chunk = 100;
$f = fopen($file, 'r');
while (!feof($f)) {
for ($i = 0; $i < $chunk; $i++) {
$tmp = fgets($f);
if ($tmp !== false) {
$data[] = $tmp;
} else {
//No more data, break out of the inner loop
break;
}
}
//Process your data
$data = array();
}
fclose($f);
If by "pause", you mean that you really want to pause execution of your script, use sleep or some of its variants: http://php.net/manual/en/function.sleep.php