PHP Iterating CSV with different columns - php

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);

Related

Show data assigned to variable from a CSV

I'm loading a CSV file and looping over each line. I want to assign variables to each column (shown in the list line), then in the first instance, show each lines $project data. So essentially that will give me each project code per line.
I'll be using the other variables but just want this one working for now.
There should be 1000 projects but it's only showing one, where am I going wrong?
<?php
$row = 1;
if (($handle = fopen("users.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, ",")) !== FALSE) {
$num = count($data);
$row++;
list($project, $rod, $rom, $asm, $contract, $site, $town, $postcode, $country) = $data;
echo $contract;
}
fclose($handle);
}
?>
in the while, just use
$project = $data[0];
Each time you call fgetcsv in your while statement, this reads the next line from the csv file. So you can either use...
<?php
if (($handle = fopen("users.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {
list($project, $rod, $rom, $asm, $contract, $site, $town, $postcode, $country) = $data;
echo $project.PHP_EOL;
}
fclose($handle);
}
?>
Or to get a list of the projects...
<?php
if (($handle = fopen("users.csv", "r")) !== FALSE) {
$projects = [];
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {
list($project, $rod, $rom, $asm, $contract, $site, $town, $postcode, $country) = $data;
$projects[] = $project;
}
fclose($handle);
print_r($projects);
}
?>

Display lines in reverse order fgetcsv

How do I display lines in reverse order?
CSV file:
column1;column2;column3
cell1;cell1;cell1
cell2;cell2;cell2
cell3;cell3;cell3
It should appear like this:
column1;column2;column3
cell3;cell3;cell3
cell2;cell2;cell2
cell1;cell1;cell1
Code:
if (($handle = fopen($path, 'r')) !== FALSE)
{
echo '<table class="table table-striped table-bordered"><thead>';
// Get headers
if (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
{
echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
}
echo '</thead><tbody>';
// Get the rest
while (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
{
echo '<tr><td>'.implode('</td><td>', $data).'</td></tr>';
}
fclose($handle);
echo '</tbody></table>';
}
Thanks in advance.
Collect first
$collect = array();
while (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
{
$collect[]= '<tr><td>'.implode('</td><td>', $data).'</td></tr>';
}
echo implode(PHP_EOL,array_reverse($collect));
Reverse the array at the end.
Here what you need to do: instead of direct echoing row - store it to a variable:
// Get the rest
$rest = '';
while (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
{
// main trick here - add every new row BEFORE old ones
$rest = '<tr><td>'.implode('</td><td>', $data).'</td></tr>' . $rest;
}
// echo gathered data
echo $rest;

Edit first line CSV with PHP

I want to edit the first line (column titles) of an CSV file. Only one problem, the script I have is replacing everything. I've tried to search for a solution, but no luck.
Script:
<?php if(isset($_FILES["file"]["tmp_name"])){
$newCsvData = array();
if (($handle = fopen("".$_FILES["file"]["tmp_name"]."", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $base = array("EAN","article","status");
$replacements = array(1=> "SKU");
$basket = array_replace($base, $replacements);
$newCsvData[] = $basket;
}
fclose($handle);
}
$handle = fopen("export/".$_FILES["file"]["name"]."", "w");
foreach ($newCsvData as $line) {
fputcsv($handle, $line);
}
fclose($handle); } else{ echo" ";} ?>
Does someone know what I'm doing wrong?
You should try:
$first = true;
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$base = array("EAN", "article", "status");
$replacements = array(1 => "SKU");
if($first){
$data = array_replace($base, $replacements);
$first = false;
}
$newCsvData[] = $data;
}
$first is a flag to detect just first row and replacing $data array values with titles array. Then you should push $data to $newCsvData. So only first row will replace by new values and other rows will remain as same data.

Read header of CSV separately

I am reading a large CSV file through fgetcsv(). I want to read the header of the file and the data separately. Below is my code. Any help?
$msg_row = 1;
while (($result = fgetcsv($msg_file,1000, ",")) !== false)
{
$msg_data[] = $result;
$msg_row++;
}
So call it once first?
$msg_row = 1;
$header = fgetcsv($msg_file, 1000, ",");
while (($result = fgetcsv($msg_file, 1000, ",")) !== false)
{
$msg_data[] = $result;
$msg_row++;
}

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

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';
}
?>

Categories