PHP dynamically create CSV: Skip the first line of a CSV file - php

I am trying to import a CSV file. Due to the program we use, the first row is basically all headers that I would like to skip since I've already put my own headers in via HTML. How can I get the code to skip the first row of the CSV? (the strpos command is to cut off the first field in all the rows.)
<?php
$row = 1;
if (($handle = fopen("ptt.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
if(strpos($data[$c], 'Finished') !== false) {
$c++;
echo "<TR> <TD nowrap>" . $data[$c] . "</ TD>"; }
Else{
echo "<TD nowrap>" . $data[$c] . "</ TD>";
}
}
}
fclose($handle);
}
?>

Rather than using if condition for checking whether it is the first row, a better solution is to just add an extra line of code before the line from where the while loop starts as shown below :
....
.....
fgetcsv($handle);//Adding this line will skip the reading of th first line from the csv file and the reading process will begin from the second line onwards
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
.......
.......
It is just as simple......

As you are keeping track of the row number anyway, you can use continue to skip the rest of the loop for the first row.
For example, add this at the start of your while loop (just above $num = count($data)):
if($row == 1){ $row++; continue; }
There are other ways to do this, but just make sure that when you continue, $row is still being incremented or you'll get an infinite loop!

Please use the following lines of code
$flag = true;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($flag) { $flag = false; continue; }
//your code for insert
}
Having the flag variable as true and setting it to false will skip the first line of the CSV file. This is simple and easy to implement.

put this inside your while loop:
if ($row == 1) continue;

Add this in the body of the while loop above the $row++;:
if ($row == 1) {
continue;
}

$count = 0;
while (($fields = fgetcsv($handle, 0, ",")) !== FALSE) {
$count++;
if ($count == 1) { continue; }

this worked for me:
$count = 0;
while(! feof($file))
{
$entry = fgetcsv($file, 0, ';');
if ($count > 0) {
//skip first line, header
}
$count++;
}

use this code
// mysql hostname
$hostname = 'localhost';
// mysql username
$username = 'root';
// mysql password
$password = '';
if (isset($_FILES['file']))
{
// get the csv file and open it up
$file = $_FILES['file']['tmp_name'];
//$handle is a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen().
$handle = fopen($file, "r");
try {
// Database Connection using PDO
$dbh = new PDO("mysql:host=$hostname;dbname=clasdb", $username, $password);
// prepare for insertion
$STM = $dbh->prepare('INSERT INTO statstrackertemp (ServerName, HiMemUti, AvgMemUti, HiCpuUti, AvgCpuUti, HiIOPerSec, AvgIOPerSec, HiDiskUsage, AvgDsikUsage) VALUES (?, ?, ?, ?, ?,?, ?, ?, ? )');
if ($handle !== FALSE)
{
// fgets() Gets a line from file pointer and read the first line from $handle and ignore it.
fgets($handle);
// created loop here
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
{
$STM->execute($data);
}
fclose($handle);
}
}
catch(PDOException $e)
{
die($e->getMessage());
}
echo 'Data imported';
}
else
{
echo 'Could not import Data';
}
?>

Related

PHP: Remove a row from a CSV if ID occurs multiple times and a column has a specific value

I have data as below in a CSV file. The green lines are what I'd like to keep.
Basically if someone has a single line, I want to keep it.
If they have multiple lines, I want to remove any where the 3rd column is A - Fully Fit.
After running through the whole file, I then want to save it over the original.
I tried writing the code but not sure if it's a Friday but the logic is escaping me at the moment.
There could be just a single line or there could be dozens. So if an ID has 1000 rows, I would just want to delete the rows for that ID where the 4th column is "A - Fully Fit"
UPDATE
This code works but not sure if it's the most optimal
// DECLARE ARRAYS
$a = Array();
$b = Array();
$c = Array();
// LOOP THROUGH FILE AND COLLECT DUPLICATES
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($line = fgetcsv($handle, 4096, ",")) !== FALSE) {
$a[$line[1]][] = 'SHAKKA';
}
foreach ($a as $k=>$v) {
if (count($v)>1) {
$b[] = $k;
}
}
}
// IF A DUPLICATE THEN REMOVE ROWS THAT ARE 'A - Fully Fit'
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($golly = fgetcsv($handle, 4096, ",")) !== FALSE) {
if (in_array($golly[1],$b) && $golly[3] == 'A - Fully Fit') {
}
else {
$c[] = $golly;
}
}
}
fclose($handle);
// WRITE THE FILE
$fp = fopen($filename, 'wa+');
foreach ($c as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
<?php
if (($handle = fopen($filename, "r")) !== FALSE) {
$new_rows = [];
$hash_ids = [];
while (($line = fgetcsv($handle, 4096, ",")) !== FALSE) {
if($line[3] === 'A - Fully Fit'){
if(isset($hash_ids[$line[1]])) continue;
$hash_ids[$line[1]] = true;
}
$new_rows[] = $line;
}
fclose($handle);
// WRITE TO THE FILE
$fp = fopen($filename, 'wa+');
foreach ($new_rows as $current_row) {
fputcsv($fp,$current_row);
}
fclose($fp);
}
In the above code, we maintain a hash(associative array) for each ID. If we have already come across with an ID with A - Fully Fit, then we skip the row, else we add it to the list.

combine echoes to echo a string as valid html

<?php
// link to Google Docs spreadsheet
$url='https://docs.google.com/spreadsheets/d/1_4d-MPxTUOVZbxTOlhjXv1ebTlBPQ-_JrYUlS1rqX5Q/pub?output=csv';
// open file for reading
if (($handle = fopen($url, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$totalrows = count($data);
for ($row=0; $row<=$totalrows; $row++)
{
if ( (strlen($data[$row])>0))
{
echo '<dt><span class="icon"></span>'.$data[$row].'</dt><dd>'.$data[$answer].'</dd>';
}
}
}
fclose($handle);
}
?>
So I have this code that takes each cell from a google sheets file but It echoes them one at a time. I need to concatenate them into one string and pass that string to a js script so I need to echo them all at once. I don't know much php so I'm having a hard time deciphering the echo line.
You can define a variable and append strings to it:
<?php
// link to Google Docs spreadsheet
$url='https://docs.google.com/spreadsheets/d/1_4d-MPxTUOVZbxTOlhjXv1ebTlBPQ-_JrYUlS1rqX5Q/pub?output=csv';
// Define variable which will hold your data.
$html = "";
// open file for reading
if (($handle = fopen($url, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$totalrows = count($data);
for ($row=0; $row<=$totalrows; $row++)
{
if ( (strlen($data[$row])>0))
{
// Append your data to $html variable
$html .= '<dt><span class="icon"></span>'.$data[$row].'</dt><dd>'.$data[$answer].'</dd>';
}
}
}
fclose($handle);
}
//Do whatever you want with $html variable.
?>

PHP Iterating CSV with different columns

I have a CSV defined like the data this.
"PID", "FName", "LName", "Email"
2425751712402934017,
1037862, "Jason", "Van Hooser", "jvanhooser#example.com"
961741, "Alana", "Traxler", "atraxler#example.com"
1100854, "Emily", "Walcheck", "ewalcheck#example.com"
1166892, "Mary", "Thomas", "mthomas#example.com"
8853065679823467777,
1179079, "Donna", "Thimm", "dthimm#example.com"
927671, "Lillian", "Wasson", "lwasson#example.com"
1175139, "Barry", "Tollison", "btollison#example.com"
1058086, "Christina", "Viktorin", "cviktorin#example.com"
What I need to do is iterate through it and when it comes to the lines where there is only the PID field with the long number, I need to store that in a variable ($wkey) and then use it in an insert statement. I know we could put the value on each row but the process that outputs the file cannot do that.
Hwere is my code:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($flag) {
$flag = false;
continue;
}
$import = "INSERT into exp_wb_bulk_reg(`WKey`,`PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
// Use the sql to insert into the table
}
fclose($handle);
How would I modify this to do what I need?
Here's working code:
// skip header line
$data = fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// get wkey for lines that has empty second column
if(trim($data[1]) == "") {
$wkey = $data[0];
}
if(trim($data[1]) != "") {
$import = "INSERT into exp_wb_bulk_registrations(`WebinarKey`, `PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
echo $import."<br />";
}
}
fclose($handle);
You could just check the size of $data array. Something like:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if(count($data) == 4){
$import = "INSERT into exp_wb_bulk_reg(`WKey`,`PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
// Use the sql to insert into the table
} else if(count($data) == ?) {
//DO STUFF
}
}
fclose($handle);
Here's my variant:
$wkey = ''; // just for sure
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
if(count($data)==1) { // hey, we found a wKey! let's remember it
$wkey = $data[0]; continue;
}
$import = "INSERT into exp_wb_bulk_reg(`WKey`,`PID`,`FName`,`LName`, `Email`,`status`) "
. "values($wkey, '$data[0]','$data[1]','$data[2]','$data[3]','I')";
}
fclose($handle);

Skipping blank rows with fopen();

I currently have some code like this:
$handle = fopen($_FILES['file']['tmp_name'], "r");
$i = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
if($i > 0) {
$sql = "
insert into TABLE(A, B, C, D)
values ('$data[0]', '$data[1]', '$data[2]', '$data[3]')
";
$stmt = $dbh -> prepare($sql);
$stmt->execute();
}
$i++;
}
fclose($handle);
This allows me to write to a certain table the contents of a CSV file, excluding the first row where all the names are. I want to be able to extract only the filled rows. How would I use so using this code?
fgetcsv returns an array consisting of a single null if the rows are empty
http://www.php.net/manual/en/function.fgetcsv.php
so you should be able to do a check based on that.
if ($data[0]===null)
{
continue;
}
or something like that
fgetcsv() returns an array with null for blank lines so you can do something like below.
$handle = fopen($_FILES['file']['tmp_name'], "r");
$i = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
if (array(null) === $data) { // ignore blank lines
continue;
}
if($i > 0) {
$sql = "
insert into TABLE(A, B, C, D)
values ('$data[0]', '$data[1]', '$data[2]', '$data[3]')
";
$stmt = $dbh -> prepare($sql);
$stmt->execute();
}
$i++;
}
fclose($handle);
Based on the documentation, fgetcsv will return an array consisting of a single null value for empty rows, so you should be able to test the return value against that and skip blank lines that way.
The following example code will skip processing blank lines. Note that I have changed the file and removed some other logic to make it more easily testable.
<?php
$handle = fopen("LocalInput.txt", "r");
$i = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
if($data== array(null)) continue;
var_dump($data);
$i++;
}
fclose($handle);
?>

get a column data into a text file one by one?

the csv data as the following:
(first line) price url
(second line) $10 src="http://www.test.com/1455/"||src="http://www.test.com/image/1456/"||
(third line) $20 src="http://www.test.com/2260/"||src="http://www.test.com/2261/"||
.... ........
now i want to put all the data from the url column into a text file. and shows the data one by one. namely:
http://www.test.com/1455/
http://www.test.com/image/1456/
http://www.test.com/2260/
http://www.test.com/2261/
....
now,i am stucked.
a, i don't know how to prevent outputting the first line.
b,i don't know how to get the url, and put them i a text file one by one.
first i using the following code to output the data to the screen.
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo $data[1] . "<br />\n";
}
fclose($handle);
}
the above code also output the first line (url). i don't want to output it. how should i do.
thank you.
You're very close! I have modified your code just slightly to do what you're trying to do. Essentially you need a second file handler for the output. You can open that as append mode so that write append to the end of the file. As for not echoing the header, you just make sure that row is greater than the first row. Hope it helps!
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE && ($handle2 = fopen("output.txt", 'a')) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($row > 1) {
fwrite($handle2, "{$data[1]}\n");
}
$row++;
}
fclose($handle);
fclose($handle2);
}
// Skips the first line of the CSV - outputting the second "column" of data.
$row = 0;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row > 0 ) {
echo $data[1] . "<br />\n";
}
$row++;
}
fclose($handle);
}

Categories