How to read CSV line by line and output with php - php

I have a CSV file that contains four data fields:
date;place;time;event
First one is date, as you can see.
I need to read CSV line by line, compare DATE with current date and output ten lines starting from the line with current date.
I tried this code:
<?php
date_default_timezone_set("Europe/Zagreb");
$today = date('Ymd');
$file_handle = fopen("data.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024,";");
if ($line_of_text[0] >= $today) echo $line_of_text[0] . "-" . $line_of_text[1]. "-" . $line_of_text[2] . "-" . $line_of_text[3] . "<BR>";
}
fclose($file_handle);
?>
But I can't break that after 10 lines. I used YYYYMMDD date format in CSV and code so basically I work with numbers, not dates.

Try this:
date_default_timezone_set("Europe/Zagreb");
$today = date('Ymd');
$file_handle = fopen("data.csv", "r");
$counter = 0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024,";");
if ($line_of_text[0] >= $today) {
echo $line_of_text[0] . "-" . $line_of_text[1]. "-"
. $line_of_text[2] . "-" . $line_of_text[3] . "<br />";
$counter++;
}
if ($counter == 10) break;
}
fclose($file_handle);

if condition should be fixed by adding strtotime before you can compare:
if (strtotime($line_of_text[0]) >= strtorime($today))
Your corrected piece of code will be:
$counter = 0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024,";");
if (strtotime($line_of_text[0]) >= strtotime($today)) {
echo $line_of_text[0] . "-" . $line_of_text[1]. "-" . $line_of_text[2]
. "-" . $line_of_text[3] . "<BR>";
$counter++;
}
if ($counter == 10) break;
}

Related

php Switch/case doesn't work

I tried to find my answer in the other switch/case question. But i don't find the solution.
I got a switch that split my date values in 4 different quarters.
But when i want to print it out, it doesn't work. I don't know what i'm doing wrong.
is this a typo or?
Thanks in advance.
MY CODE
while (odbc_fetch_row($result)) { // while there are rows
$overweight = odbc_result($result, "Weight1") - 44000;
//$total_overweight += $overweight;
$date = date("Y-m-d", strtotime(odbc_result($result, "Date1")));
$companies[] = odbc_result($result, "String3");
$weight = odbc_result($result, "Weight1");
$item['nrplaat'] = odbc_result($result, "String1");
$item['tptcode'] = odbc_result($result, "String3");
$item['chrononr'] = odbc_result($result, "String15");
$item['projectcode'] = odbc_result($result, "String4");
$item['projectnaam'] = odbc_result($result, "String8");
$item['1eweging'] = $weight;
$item['overweighted'] = $overweight;
$item['date'] = $date;
$item['2eweging'] = odbc_result($result, "Weight2");
$item['netto'] = odbc_result($result, "Nett");
switch($weight){
case($weight > '44000' && $weight <= '44500'):
$item['class'] = 'lichtgroen';
case($weight > '44500' && $weight <= '45000'):
$item['class'] = 'groen';
case($weight > '45000' && $weight <= '46000'):
$item['class'] = 'donkergroen';
case($weight > '46000' && $weight <= '47000'):
$item['class'] = 'bruingroen';
case($weight > '47000' && $weight <= '48000'):
$item['class'] = 'lichtbruin';
case($weight > '48000' && $weight <= '49000'):
$item['class'] = 'bruin';
case($weight > '49000' && $weight <= '50000'):
$item['class'] = 'lichrood';
case($weight > '50000'):
$item['class'] = 'rood';
}
switch($date){
case($date > $s_year.'-'.$quart1 && $date <= $s_year.'-'.$quart2):
$item['quarter'] = '1'; //kwartaal 1
case($date > $s_year.'-'.$quart2 && $date <= $s_year.'-'.$quart3):
$item['quarter'] = '2'; ////kwartaal 2
case($date > $s_year.'-'.$quart3 && $date <= $s_year.'-'.$quart4):
$item['quarter'] = '3'; ////kwartaal 3
case($date > $s_year.'-'.$quart4 && $date <= $s_year.'-'.$end):
$item['quarter'] = '4'; ////kwartaal 4
}
//$item['quarter'] = 1; WHEN I DO THIS, ALL RESULTS WILL PRINT OUT!!!
switch($item['quarter']){
case '1':
print "<tr>\n";
print " <td>" . $item['nrplaat'] . "\n";
print " <td>" . $item['tptcode'] . "\n";
print " <td>" . $item['chrononr'] . "\n";
print " <td>" . $item['projectcode'] . "\n";
print " <td>" . $item['projectnaam'] . "\n";
print " <td>" . $item['1eweging'] . "\n";
print " <td>" . "<span class=\"status\">".$item['class']."</span>" ."\n";
print " <td>" . $item['overweighted'] . "\n";
print " <td>" . $item['date'] . "\n";
print " <td>" . $item['2eweging'] . "\n";
print " <td>" . $item['netto'] . "\n";
print "</tr>\n";
break;
}
}
Use break;
case($date > $s_year.'-'.$quart1 && $date <= $s_year.'-'.$quart2):
$item['quarter'] = '1';
break;
Perhaps it's because you don't have break; in each switch case.
Try to add some break;
See here for switch in php.
You should add a break; statement at the end of each case.
You should add 'break' after 'case'. it is very important if you have some 'case'. Please understand the concept of switch statements, you can learn from http://php.net/manual/en/control-structures.switch.php.
If you have some 'case' and you don't use 'break', it mean the next case will be proceed too. If you using 'break' after 'case', the switch process will finish and not proceed to next case. Maybe you should learn about 'continue' too :)

PHP Comparing 0 does not work

I'm trying to set a checkbox as checked in php based on an hour fields from a comma separated value string. It works well for 1-23 but for some reason hour 0 always displays as checked:
<?php
myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
if(count($myhours) > 0) {
for($h = 0; $h <= count($myhours); $h++) {
if((int)$hour == (int)$myhours[$h]) {
$checked = " checked ";
break;
}
}
} else {
$checked = "";
}
if(strlen($hour) == 1) {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";
} else {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
}
$checked = "";
}
?>
The problem is straightforward; look at the outer loop:
for ($hour = 0; $hour <= 23; $hour++) {
Consider only the first iteration, so $hour is int(0). Further in the code:
if(count($myhours) > 0) {
for($h = 0; $h <= count($myhours); $h++) {
Pay close attention to the loop condition:
$h <= count($myhours)
Consider the last iteration of that loop, so $h equals the size of your array.
if ((int)$hour == (int)$myhours[$h]) {
At this point $myhours[$h] is undefined because the array index is out of bounds (and a notice would have been emitted) and so (int)$myhours[$h] becomes (int)null which is int(0). The comparison is therefore always true when $hour has the value of int(0).
The solution is to change the loop condition to:
$h < count($myhours)
Not exactly and answer, but your code could be reduced to this:
$myhours = array(0, 10, 13, 20);
for($hour = 0; $hour <= 23; $hour++) {
echo '<td><input type="checkbox"' . ( in_array($hour, $myhours) ? ' checked' : '' ) . ' value="' . $hour . '" onchange="updatehour(' . $_REQUEST['user'] . ', this.checked, ' . $hour . ')">' . str_pad($hour, 2, '0', STR_PAD_LEFT) . ':00</td>';
}
No need for a second loop and more variables here. Also be aware to not output values from $_REQUEST directly without any check.
Demo
Try before buy
Problem solved. It was actually the count($myhours) that was causing the problem. Basically even with an empty string it still returns an array with 1 element. Changed to check if count($myhours) > 1 and everything is working as expected:
<?php
$myhours = explode(",", substr($arruser['arhours'],0,strlen($arruser['arhours']) - 1));
$checked = "";
for($hour = 0; $hour <= 23; $hour++) {
if(count($myhours) > 1) {
for($h = 0; $h <= count($myhours); $h++) {
if((int)$hour == (int)$myhours[$h]) {
$checked = " checked ";
break;
}
}
} else {
$checked = "";
}
if(strlen($hour) == 1) {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">0$hour:00</td>";
} else {
echo "<td><input type=checkbox " . $checked . " value=" . $hour . " onchange=\"updatehour(" . $_REQUEST['user'] . ",this.checked, '" . $hour . "')\">$hour:00</td>";
}
$checked = "";
}
?>

simple pagination with this script?

Hello stackoverflow I was wondering if it is possible to get a simple pagination thingy with this little script? is it possible to get an example? this script takes all csv files in a folder and shows it on a webpage. The only problem is if the csv has 2000 records each csv then the page crashes. can I like show each csv file on a seperate page?
<?php
$arrFiles = glob("../Csv_folder/EMCY_GEN/*.csv");
$arrSortedFiles = array();
foreach($arrFiles as $strFileName) {
$arrSortedFiles[$strFileName] = filemtime($strFileName);
}
arsort($arrSortedFiles);
foreach(array_keys($arrSortedFiles) as $strFileName)
{
$file_handle = fopen($strFileName, "r");
echo "<th><font size='3pt'>".date ("F d Y H:i:s.", filemtime($strFileName))."</td></tr></font></th>";
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
echo '<tr><td>' . $line_of_text[0] . '</td><td>' . $line_of_text[1] . '</td><td>' . $line_of_text[2] . '</td><td>' . $line_of_text[3] . '</td><td>' . $line_of_text[4] . '</td></tr>' ;
}
fclose($file_handle);
}
?>
You want to not have a loop printing out the contents of each CSV. Have an index page that displays the files then link to another page that dynamically loads the CSV.
$arrFiles = glob("../Csv_folder/EMCY_GEN/*.csv");
$leg = count($arrFiles);
while($num < $leg){echo $arrFiles[$num]; $num = $num + 1};

Formatting String in PHP

I am trying to display numbers retrieved from the database, in a specific format in a text box.
There are two ways in which the numbers can be displayed.
When the total numbers are 10
in database (4608061019) Expected output 46-0806-1019
When the total numbers are 13
in database (4608061019100) Expected output 46-0806-1019-100
My progress so far:
While saving the value into the database I am using
preg_replace("/[^0-9]/","",$string); // to make sure all hardcoded "-" are removed while storing.
One possible (regex-using) approach:
$str = '4608061019';
$formatted = preg_replace(
'/(^\d{2}|\d{4})(?!$)/', '$1-', $str);
// 46-0806-1019
Demo. This function doesn't check the string's length - it just adds a hyphen after each relevant sequence of symbols (2 right after the beginning, 4 afterwards).
Easy! If you are sure that there are only these two options, then you can do this way:
Convert the number to an array of numbers:
$number = str_split($number);
Check the length:
if (count($number) == 10)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9];
else if (count($number) == 13)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9] . "-" . $number[10] . $number[11] . $number[12];
Return the number:
return $number;
The full function here:
function tokenize($number)
{
$number = str_split($number);
if (count($number) == 10)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9];
else if (count($number) == 13)
$number = $number[0] . $number[1] . "-" . $number[2] . $number[3] . $number[4] . $number[5] . "-" . $number[6] . $number[7] . $number[8] . $number[9] . "-" . $number[10] . $number[11] . $number[12];
return $number;
}
Output
echo tokenize(4608061019);
echo tokenize(4608061019100);
Output
46-0806-1019
46-0806-1019-100
Fiddle: http://codepad.viper-7.com/EVWeFR
Another alternative solution:
$parts = array(2,4,4,3);
$string = "4608061019100";
$i = 0;
$newString = '';
foreach ($parts as $part) {
$newString.=substr($string, $i, $part) ."-";
$i = $i+$part;
}
$newString = rtrim($newString, "-");
Output is:
string '46-0806-1019-100' (length=16)
Works for 46-0806-1019 too.
try it:
//$number = '4608061019';
$number = '4608061019100';
function formatImportantNumber($theNumber){
$formatedNumber = '';
if(strlen($theNumber)==10){
//46-0806-1019
$formatedNumber = substr($theNumber, 0, 2).'-'.substr($theNumber, 2, 4).'-'.substr($theNumber, 6, 4);
}elseif(strlen($theNumber)==13){
//46-0806-1019-100
$formatedNumber = substr($theNumber, 0, 2).'-'.substr($theNumber, 2, 4).'-'.substr($theNumber, 6, 4).'-'.substr($theNumber, 10, 3);
}else{
die('Invalid number formated')
}
return $formatedNumber;
}
echo formatImportantNumber($number);

Change a value of a variable within an array variable value in php

I am trying to update a variable value that is within an array variable value.
You will see I am writing out a file with: file_put_contents(). The implode("\r\n", $contents)... contains the $contents variable.
I need $body_file_count to increment every iteration of the if ($i == $per_file) {...
It's pretty evident the $contents array cannot update a variable value in this case $body_file_count.
$body_file_count is the number of files outputted. It's actually the same number in the file title: $file_count...
Basically, I just need to write the $body_file_count to the:
$default_contents=$contents=array("BODY CONTENT TOP . "$body_file_count" . ");
on each if ($i == $per_file) { iteration. Obviously I could scrap $body_file_count if I could pass $file_count to the $content as $file_count is updating the title as expected.
$body_file_count = 0;
$footer = "FOOTER";
$default_contents = $contents = array("BODY CONTENT TOP . "$body_file_count" . ");
while ($row = mysql_fetch_array($result)) {
$line = "...";
$contents[] = $line; // Each array element will be a line in the text file
$i++;
$recs++;
if ($i == $per_file) {
$contents[] = $footer; // Add the footer to the end
file_put_contents($_POST["a"] . "-#" . $file_count . "-" . date('Y') . "-" . $_POST["b"] . "-" . $recs . "-" . $txtdate . '.txt', implode("\r\n", $contents));
$i = 0;
$recs = 0;
$contents = $default_contents;
$file_count++;
$body_file_count++;
} // End of if()
} // End of while()
First beware that you have forget to add the string concatenation operator (".") on the $default_contents initialitation
I don't know if i have understand well your question. If i have understand well your problem you can try to update the the $default_contents everytime that you change $body_file_count++
$body_file_count = 0;
$footer = "FOOTER";
$default_contents = $contents = array("BODY CONTENT TOP . " . $body_file_count . " . ");
while ($row = mysql_fetch_array($result)) {
$line = "...";
$contents[] = $line; // Each array element will be a line in the text file
$i++;
$recs++;
if ($i == $per_file) {
$contents[] = $footer; // Add the footer to the end
file_put_contents($_POST["a"] . "-#" . $file_count . "-" . date('Y') . "-" . $_POST["b"] . "-" . $recs . "-" . $txtdate . '.txt', implode("\r\n", $contents));
$i = 0;
$recs = 0;
$file_count++;
$body_file_count++;
$default_contents = array("BODY CONTENT TOP . " . $body_file_count . " . ");
$contents = $default_contents;
} // End of if()
} // End of while()
Also if you don't need for anything else this variable besides to provide an initial content then you can just take it away
$body_file_count = 0;
$footer = "FOOTER";
$contents = array("BODY CONTENT TOP . " . $body_file_count . " . ");
while ($row = mysql_fetch_array($result)) {
$line = "...";
$contents[] = $line; // Each array element will be a line in the text file
$i++;
$recs++;
if ($i == $per_file) {
$contents[] = $footer; // Add the footer to the end
file_put_contents($_POST["a"] . "-#" . $file_count . "-" . date('Y') . "-" . $_POST["b"] . "-" . $recs . "-" . $txtdate . '.txt', implode("\r\n", $contents));
$i = 0;
$recs = 0;
$file_count++;
$body_file_count++;
$contents = array("BODY CONTENT TOP . " . $body_file_count . " . ");
} // End of if()
} // End of while()

Categories