Show data assigned to variable from a CSV - php

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

Related

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;

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.
?>

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 contents of two csv files in php and merge them into a third file based on a key field

I've searched the web and looked through existing answers but cant find a solution to this one. I want to use php to do the following task. Here are my files:
csv file 1: member.csv
member1|john|smith|2009
member2|adam|jones|2007
member3|susie|rose|2002
csv file 2: classes.csv
member1|massage|swimming|weights
member2|gym|track|pilates
member3|yoga|running|stretches
I want to output a third file called file3.csv which merges the two above files together based on the key field which is the member number. the output should be like this:
member1|john|smith|2009|massage|swimming|weights
member2|adam|jones|2007|gym|track|pilates
member3|susie|rose|2002|yoga|running|stretches
the delimiter is a bar character. I want to do this just using php - no other languages.
I would be very greatful for a solution.
Matt
Read both files and store data to the array with keys: member1, ...
Write a new file lines in loop:
foreach ($firstArray as $key => $value1) {
$value2 = $secondArray[$key];
// ...
}
<?php
$data = array();
if (($handle = fopen('file1.csv', 'r')) !== FALSE) {
while (($line = fgetcsv($handle, 0, '|')) !== FALSE) {
$memberId = $line[0];
unset($line[0]);
$data[$memberId] = $line;
}
fclose($handle);
}
if (($handle = fopen('file2.csv', 'r')) !== FALSE) {
while (($line = fgetcsv($handle, 0, '|')) !== FALSE) {
$memberId = $line[0];
unset($line[0]);
$data[$memberId] = array_merge($data[$memberId], $line);
}
fclose($handle);
}
ksort($data); // not needed, but puts records in order by member
if (($handle = fopen('file3.csv', 'w')) !== FALSE) {
foreach($data as $key => $value) {
fwrite($handle, "$key|" . implode('|', $value) . "\n");
}
fclose($handle);
}
Try this. It is untested.
$arr_one = array();
if (($fp = fopen("member.csv", "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$arr_one[$data[0]] = $data;
}
fclose($fp);
}
$arr_two = array();
if (($fp = fopen("classes.csv", "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$arr_two[$data[0]] = $data;
}
fclose($fp);
}
$classes_field_count = sizeof(current($arr_two));
$members = array_keys($arr_one);
foreach ($members as $key) {
if (!isset($arr_two[$key])) {
$arr_two[$key] = range(0, ($classes_field_count - 1));
}
unset($arr_two[$key][0]);
$result_arr[$key] = array_merge($arr_one[$key], $arr_two[$key]);
}
if (($fp = fopen("file3.csv", "w")) !== FALSE) {
foreach ($result_arr as $fields) {
fputcsv($fp, $fields, '|');
}
fclose($fp);
}

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