How to specify which csv file using multiple get_cell - php

I have a page with multiple get_cell functions within it that all successfully return a single cell value from a CSV file.
However, the first CSV file specified in the first instance is the one the rest pull information from. I have at least two different CSV files I need to reference on the same page.
How do I specify the CSV file, as well as the specific cell?
<?php
if (!function_exists('get_cell')) {
function get_cell($cell, $row)
{
$file = 'CSV/filename.csv';
$row = $row - 1;
// Reset the $row if it's negative.
if ($row < 0) {
$row = 0;
}
$handle = fopen($file, "r");
$counter = 0;
while (($csvline = fgetcsv($handle, 450, ",")) != false) {
if ($counter == $row) {
$new_array = array();
$begin = 'a';
foreach ($csvline as $cellnr) {
$new_array[$begin] = $cellnr;
$begin++;
}
echo $new_array[strtolower($cell)];
}
$counter++;
}
}
}
get_cell('A', 1);
?>

You can simply pass in the file name as one of the arguments, with CSV/filename.csv as a default if you'd like:
function get_cell($cell, $row, $file="CSV/filename.csv")
{
...
}
get_cell('A', 1, "CSV/filename2.csv");

Related

Gravity forms: exporting two forms of entries data to one CSV file

I'm wondering if I can export two deferent forms entries based on the submitter id but with a specific concept,
The concept is:
If the entry title from the first form == some entry field of the other form, let's show these two entries in the exported data in one row, and so on, something like array_map in php.
I hope that you got the idea, any help to do that?
Thanks a lot,
Magdi
Use These Codes:
(first code returns data from csv file into an array)
(second code gets data from an array and save into a csv file)
function csvExporter($path) {
$csv = array();
$row = 1;
if (($handle = fopen($path, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$csv[str_pad($row,4,0,STR_PAD_LEFT)] = array();
for ($c = 0; $c < $num; $c++) {
$csv[str_pad($row,4,0,STR_PAD_LEFT)][$c] = $data[$c];
}
$row++;
}
fclose($handle);
}
return $csv;
}
function csvImporter($path,$array) {
$csvFile = fopen($path,'w+');
foreach ($array as $rows) {
$eachRow = '[';
foreach ($rows as $columns) {
$eachRow .= '\'' . trim($columns,'\'') .'\',';
}
$eachRow .= ']' . PHP_EOL;
}
fclose($csvFile);
}

How to use get_cell() more than once using php and the same csv file?

Using the code below, I can successfully pull a single piece of information from a CSV file, detailing a specific row and column i.e C,2.
If I repeat this function on the same page, I get the error message:
"Fatal error: Cannot redeclare get_cell() (previously declared in myphpfile.php:50) in myphpfile.php on line 187"
Is it possible to pick more than one cell from a CSV file using php?
Here's the code:
<?php
function get_cell($cell, $row)
{
$file = 'CSV/mycsvfile.csv';
$row = $row -1;
// Reset the $row if it's negative.
if($row < 0)
{
$row = 0;
}
$handle = fopen ($file, "r");
$counter = 0;
while (($csvline = fgetcsv($handle, 450,",")) != false)
{
if($counter == $row)
{
$new_array = array();
$begin = 'a';
foreach($csvline as $cellnr)
{
$new_array[$begin] = $cellnr;
$begin++;
}
echo $new_array[strtolower($cell)];
}
$counter++;
}
}
get_cell('C', 2);
?>

How to import just two cells from CSV file to PHP

I have a CSV file with lots of data in it, from which I create many different tables using
PHP, specifying certain rows and columns.
However, I have a requirement for only showing two cells, A7 and A8. The code I currently use requires fields for table head and table data, which on this occasion I don't need.
What is the most effect way of doing this?
<?php
function get_cell($cell, $row)
{
$file = 'stuff.csv';
$row = $row -1;
// Reset the $row if it's negative.
if($row < 0)
{
$row = 0;
}
$handle = fopen ($file, "r");
$counter = 0;
while (($csvline = fgetcsv($handle, 450,";")) != false)
{
if($counter == $row)
{
$new_array = array();
$begin = 'a';
foreach($csvline as $cellnr)
{
$new_array[$begin] = $cellnr;
$begin++;
}
echo $new_array[strtolower($cell)];
}
$counter++;
}
}
get_cell('a', 1);
echo '<br>';
get_cell('b', 1);
?>

How can I parse a CSV into array with first value as key?

So I have a CSV file that looks like this:
12345, Here is some text
20394, Here is some more text
How can I insert this into an array that looks like so
$text = "12345" => "Here is some text",
"20394" => "Here is some more text";
This is what I currently had to get a single numerical based value on a one tier CSV
if ($handle = fopen("$qid", "r")) {
$csvData = file_get_contents($qid);
$csvDelim = "\r";
$qid = array();
$qid = str_getcsv($csvData, $csvDelim);
} else {
die("Could not open CSV file.");
}
Thanks for the replies, but I still see a potential issue. With these solutions, wouldn't the values store in this way:
$array[0] = 12345
$array[1] = Here is some text 20394
$array[2] = Here is some more text
If I tried this on the example csv above, how would the array be structured?
You can use fgetcsv() to read a line from a file into an array. So something like this:
$a = array();
$f = fopen(....);
while ($line = fgetcsv($f))
{
$key = array_shift($line);
$a[$key] = $line;
}
fclose($f);
var_dump($a);
Assuming that the first row in the CSV file contains the column headers, this will create an associative array using those headers for each row's data:
$filepath = "./test.csv";
$file = fopen($filepath, "r") or die("Error opening file");
$i = 0;
while(($line = fgetcsv($file)) !== FALSE) {
if($i == 0) {
$c = 0;
foreach($line as $col) {
$cols[$c] = $col;
$c++;
}
} else if($i > 0) {
$c = 0;
foreach($line as $col) {
$data[$i][$cols[$c]] = $col;
$c++;
}
}
$i++;
}
print_r($data);
If you are reading a file I can recommend using something like fgetcsv()
This will read each line in the CSV into an array containing all the columns as values.
http://at2.php.net/fgetcsv
$csv_lines = explode('\n',$csv_text);
foreach($csv_lines as $line) {
$csv_array[] = explode(',',$line,1);
}
edit - based on code posted after original question:
if ($handle = fopen("$qid", "r")) {
$csvData = file_get_contents($qid);
$csvDelim = "\r"; // assume this is the line delim?
$csv_lines = explode($csvDelim,$csvData);
foreach($csv_lines as $line) {
$qid[] = explode(',',$line,1);
}
} else {
die("Could not open CSV file.");
}
With your new file with two columns, $qid should become an array with two values for each line.
$csvDelim = ",";
$qid = str_getcsv($csvData, $csvDelim);
$text[$qid[0]] = $qid[1];

submit file via form and handle it in a php function

I need to upload a file (in this case a csv file) and load the contents of it into the following function:
function csv2xml($file, $container = 'data', $rows = 'row')
{
$r = "<{$container}>\n";
$row = 0;
$cols = 0;
$titles = array();
while (($data = fgetcsv($file, 1000, ',')) !== FALSE)
{
if ($row > 0) $r .= "\t<{$rows}>\n";
if (!$cols) $cols = count($data);
for ($i = 0; $i < $cols; $i++)
{
if ($row == 0)
{
$titles[$i] = $data[$i];
continue;
}
$r .= "\t\t<{$titles[$i]}>";
$r .= $data[$i];
$r .= "</{$titles[$i]}>\n";
}
if ($row > 0) $r .= "\t</{$rows}>\n";
$row++;
}
$r .= "</{$container}>";
return $r;
}
This is how im calling the function
csv2xml($_POST['file'], $container = 'wholething', $rows = 'item');
In the form the input box's name is file
I get the following Warning:
fgetcsv() expects parameter 1 to be resource, null given
You need to open the file first, eg:
$filePointer = fopen($file, "r"); // read-only
Then use:
while (($data = fgetcsv($filePointer, 1000, ',')) !== FALSE)
to retrieve your data.
Note that you'll probably want to check out PHP's file upload information to make sure you're using the $_FILES array to get your uploaded file. and not just $_POST.
#richsage already answered the question. If you still have problems, visit the documentation for a working example. I just wanted to point out your function call:
csv2xml($_POST['file'], $container = 'wholething', $rows = 'item');
Although it works, this is not how you call functions.
csv2xml($_POST['file'], 'wholething', 'item');
Is what you mean to do.

Categories