Read header of CSV separately - php

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++;
}

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

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

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

How do i remove the top line in a CSV file (the coloumn headers)?

I have put together a script which will upload a CSV file and then extract the data into an already made table. I want to make it so the first line(the column headers) will not be inserted into the table, but the rest of the data will be.
$fp = fopen($_SESSION['filename'],"r");
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE)
{
$import="INSERT into csv_table(name,address,age) values('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
}
fclose($fp);
this is the part of the code i use to extract the data from the csv file.
Thank You very much for any help with this matter!
Just put the following before the while loop to read the first line:
fgetcsv($fp, 1000, ",");
Thereafter the while loop starts with the second line instead.
Underthink it.
Create a boolean flag on the outside, and toggle it once you enter the loop instead of importing, using an if statement.
Simply do a blank read as such:
$fp = fopen($_SESSION['filename'],"r");
$headerLine = true;
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE)
{
if($headerLine) { $headerLine = false; }
else {
$import="INSERT into csv_table(name,address,age) values('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
}
}
fclose($fp);
You can use out of loop fgetcsv() function and then, after your array, print value second line:
if (($handle = fopen($target_file, "r")) !== FALSE) {
$i=1;
fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo "<pre>";
print_r($data);
echo "</pre>";
$i++;
}
}

Categories