submit file via form and handle it in a php function - php

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.

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 specify which csv file using multiple get_cell

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

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

unable to write csv from array

I read most of the discussions about my problem but I do not find a solution.
So, I have a .csv file from which I read, extract all the content and populate a multidimensional array. That is the code I wrote to do that:
if (($handle = fopen("dateRegion.csv", "r")) !== FALSE) {
# Set the parent multidimensional array key to 0.
$pr = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
# Count the total keys in the row.
$count = count($data);
# Populate the multidimensional array.
for ($x = 0; $x < $count; $x++) {
$brim[$pr][$x] = $data[$x];
}
$pr++;
}
fclose($handle);
}
After that, I extract the element I need and put it into another array. That array will be the content of the new .csv file.
This is the code:
$parserCsv = array();
$dip=1;
do {
$region = $brim[$dip][7];
$sex = $brim[$dip][8];
$frequency = $brim[$dip][9];
$value = $brim[$dip][10];
$parserCsv[] = array($region, $sex, $frequency, $value);
$dip++;
} while($dip <= 6336);
This is the "var_dump()" of the array:
Array(
[0] => Piemonte
[1] => maschi
[2] => 2005
[3] => 16.972)
etc.
I tried to put the content of the array $parserCsv using the method fputcsv(), with that script:
$fp = fopen('csvExtract.csv', 'w');
foreach ($parserCsv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
but it did not work. The content of the file csvExtract.csv is blank. I do not understand my mistake, I tried other solution like create the array $parserCsv like:
$parserCsv = array(
array($region), array($sex), array($frequency), array($value));
and nothing change. Does anyone have some advise?
EDIT: Edited the code with the solution suggested by mkjasinski! The code is working now.
Thanks for all the replies.
Brus
Try this:
if (($handle = fopen("dateRegion.csv", "r")) !== FALSE) {
# Set the parent multidimensional array key to 0.
$pr = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
# Count the total keys in the row.
$count = count($data);
# Populate the multidimensional array.
for ($x = 0; $x < $count; $x++) {
$brim[$pr][$x] = $data[$x];
}
$pr++;
}
fclose($handle);
}
and this:
$parserCsv = array();
$dip=1;
do {
$region = $brim[$dip][7];
$sex = $brim[$dip][8];
$frequency = $brim[$dip][9];
$value = $brim[$dip][10];
$parserCsv[] = array($region, $sex, $frequency, $value);
$dip++;
} while($dip <= 6336);
and save:
$fp = fopen('csvExtract.csv', 'w');
foreach ($parserCsv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
are you getting some errors?
Is the file open in some other software? (like MS Excel?)
Following code enters 4 records in CSV
$parserCsv = array(
array('Piemonte'),
array('maschi'),
array(2005),
array(16.972)
);
$fp = fopen('blah.csv', 'w');
foreach($parserCsv as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);

parsing a CSV as XML via PHP

I found this script which parses a CSV file to XML. Problem is it seems to only be getting the first line of data after the column headers.
function csv2xml($file, $container = 'data', $rows = 'row')
{
$r = "<{$container}>\n";
$row = 0;
$cols = 0;
$titles = array();
$handle = #fopen($file, 'r');
if (!$handle) return $handle;
while (($data = fgetcsv($handle, 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++;
}
fclose($handle);
$r .= "</{$container}>";
return $r;
}
Your CSV may be using Carriage Returns instead of Newlines, Try changing the "\n"s to "\r"s.

Categories