Trying to process information from .csv file into PHP - php

I'm trying to pull information from a .CSV file to process with PHP into a local database.
I have the following code:
<?
$csv = array_map('str_getcsv', file('red.csv'));
echo $csv[1];
?>
The first bit works, if I try to echo the array_map with print_r or var_dump - but I'm not sure how to process it this way.
I'm used to being able to loop through with a for loop where $csv is an array and [0] is the record - but right now the only thing being ECHO'd is Array
I've never worked with array_map's before - and I found the code I am using (Except for the echo obviously) elsewhere online.
How can I loop through the entire array to process each record individually?

The reason Array is being echoed is because str_getcsv returns an array. So $csv is an array with each element inside it being an array of the csv values. If you change it to
<?php
$csv = array_map('str_getcsv', file('red.csv'));
print_r($csv[0]);
?>
You will be able to see the line as an array of each csv item.

You can loop through csv with this:
if (($handle = fopen("your.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, null, ";", '"')) !== FALSE) {
// $data is an array that contains the current row
}
}
note: change the delimiter and escape characters in fgetcsv() according to your csv.

You can travel/iterate over the CSV array using this structure:
foreach( $csv as $row_id => $row_data ) {
foreach( $row_data as $cell_id => $cell_data ) {
// The next will output the same data
echo $cell_data . '\n';
echo $csv[$row_id][$cell_id] . '\n';
}
}

Please follow below code for getting data from csv, looping through each row.
<?php
$csv = array_map('str_getcsv', file('red.csv'));
//print_r($csv[0]);
foreach($csv as $key=>$v)
{
echo $csv[$key][0];//column A/0
echo $csv[$key][1];//column B/1
}
?>

Related

Foreach returns only first record, stops

This should be very simple, but I'm getting odd behavior I've never seen before. Here is the code:
<?php
$csv = array_map('str_getcsv',file('dummy.csv'));
$n=1;
foreach($csv as $key=>$val) {
$sql = "UPDATE table set field = '$val[$key]' WHERE id = $n";
echo $sql."\n";
$n++;
}
?>
The .csv file is 260 simple text phrases that show up properly with print_r($csv);. The above code gives proper output but stops after the first record. Why?
str_getcsv returns an array.
array_map also returns an array.
So, your $csv is an array with an array within it.
After your line $csv = array_map('str_getcsv',file('dummy.csv'));, add the line $csv = $csv[0]; This pulls out the inner array. Then you should get the expected results without changing the remainder of your code.

Access php array index issue

After use fgetcsv() function I get an array, then I use a foreach() and I get a "simple" associative array like:
Array
(
[ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1
)
Then I try to access any element and I fail:
echo $record['ix'];
Notice: Undefined index: ix
echo next($record); // return nothing!
Maybe is offtopic (not centred in php language) but I'm using some lib (not necessary of course from PHP commenter in http://php.net/manual/es/function.fgetcsv.php)
<?php
require "..\CsvImporter.lib.php";
$importer = new CsvImporter('my_route\\my.csv',true);
while($records = $importer->get())
{
// debug
print_r($records[0]);
exit;
foreach ($records as $record)
{
\\ ..
}
}
And my screen output is
Array ( [ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1 )
My data:
ix,radical,variant,simplified,pinyin,english,strokes
1,一,,,yi1,one,1
2,丨,,,gun3,line,1
3,丶,,,zhu3,dot,1
So how is possible I'm unable to access any key ?
As you posted your data above. Your csv importer giving you each row with comma. So you need to explode it then use however you want to use
Example code \
$i=0;
while($records = $importer->get())
{
if($i>0) //skip first row it is heading
{
$data = explode(',',$records);
print_r($data);
// now `$data[0]` contains `ix` value for your first csv row and so on
}
$i++;
}
I used some lib and the default delimiter was "\t" so something like 'ix,radical,variant,simplified,pinyin,english,strokes' was THE key and '一,,,yi1,one,1' the only value
Now, I see the problem I can do it easy:
$f = 'file.csv';
$separator = ',';
$file = file_get_contents($f);
// bi-dimensional array
$regs = array_map(function($reg){return (explode($separator,$reg));},explode("\n",$file));
Thanks all!

PHP parse CSV by columns

I would like to ask for help with this task: I have CSV for example like this:
column1$column2$column3
123$xyz$321
456$zyx$654
And I would like to parse it by PHP to Arrays by columns / headers -> for example
$column1 = {123,456}
$column2 = {xyz,zyx}
$column3 = {321,654}
Thanks everyone.
Consider the following code and explanations:
$file = file("example.csv"); // read the file to an array
$cols = array();
for ($i=1;$i<count($file);$i++) { // loop over $file,
// starting in the second line
$row = explode('$', $file[$i]); // make an array with explode
for ($j=0;$j<count($row);$j++) // loop over the $row array
array_push($cols["column".$j], $row[$j]);
// push it to the cols array
}
print_r($cols);
What are your curly brackets supposed to do? In PHP an array is formed with [].
Rather than reading the whole file to an array you could as well read each line and push it to the cols array.

Fill array with contents of csv with php

I am trying to fill a array with a csv so each field is separate part of the array, when i have filled the array and echo it out it quite literally says array for every enter.
I have a feeling that once i sort the csvfull array that the sku might need to be in loop inside the main processing loop to.
$ocuk = fopen("ocuk.csv", "r");
while (($result = fgetcsv($ocuk)) !== false)
{
$csvfull[] = $result;
}
print_r ($csvfull[0][1]);
$sku="$csvfull[1]";
while (($csv = fgetcsv($ocuk)) !== FALSE)
{
if (false === empty(array_intersect($sku, $csv)))
{
code to display the results from csv that match the $sku variable
}
}
What i need it to do is csvfull array to fill with the contents of the csv such i can then call it into the variable sku to do comparison in next part of the code.
EDIT example of what i mean
csv example
data,data2,data3,data4 etc
data10,data20,data30,data40 etc
the array would then be like this
$csvfull=array() would contain the below
array("data","data2","data3","data4");
array("data10","data20","data30","data40");
then when i call csvfull[1] it display data2 then would go onto data 20 etc
$csvfull is a 2-dimensional array. The first dimension is the rows of the CSV, the second dimension is the columns. So $csvfull[1] is an array containing all the values from the second line of the file. To get the SKU, you need to drill down to the appropriate column, e.g.
foreach ($csvfull as $row) {
$sku = $row[1];
// Do something with $sku
}
If you want to get an array of all the SKUs, you can do:
$sku = array();
foreach ($csvfull as $row) {
$sku[] = $row[1];
}
try like this:
<?php
$ocuk = fopen('clientes.csv','r');
$i=0;
while(!feof($ocuk)){
$values = fgetcsv($ocuk);
if(empty($values[1] )){ // any index which is not empty to make sure that you are reading valid row.
continue;}
$csvfull[$i] = $values;
$i++;
}
print_r($csvfull);
.
fclose($ocuk);

Foreach loop takes last value only

I am new in PHP and I have little problem. I have code like this:
$file = $_FILES['sel_file']['name'];
$chk_ext = explode(".",$file);
if(strtolower($chk_ext[1]) == "txt")
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$array = array( $data[0]);
foreach( $array as $value )
{
$number=$value;
}
$obj=new Sender("$number");
}
header("location:bulk.php?msg=send");
}
else
{
header("location:bulk.php?invalid=file");
exit();
}
$obj->Submit ();
Problem is that only last value comes out from text file in $obj=new Sender("$number");, please help me out.
fgetcsv() already return an array so: $array = array( $data[0]); just means that you only retrieve the first element of the array of fields which is $data.
In the foreach loop you should just replace the $array variable with $data.
The loop woould then look like this:
foreach( $data as $value )
{
$number=$value;
}
$obj=new Sender("$number");
means that for every element in $data, you hold it inside $number, loops again and put it again in $number overwriting it.
After the foreach loop the value of $number would be the last field of the row.
You should just put the line $obj=new Sender("$number"); inside the loop, so that every element of every row would be put in Sender.
No surprise. You loop over all the values, continually overwriting $number with the most recently retrieved value. When the loop exits, you end up with only the last one.
Probably you want something more like:
foreach($array as $value) {
$obj = new Sender($value);
}
your code also makes very little sense. You take an uploaded file, presumably CSV, read a line from it, extract the FIRSt value from that line. force the value into an array, then read back that ONE value in the array (the ONLY value in the array), and do something with it.
Even if your foreach wasn't overwriting the value, you still only have one single value to loop on anyways.
You are overwriting the contents of number each iteration. You can instead make number an array which stores each value at incrementing elements.
foreach( $array as $value )
{
$number[]=$value;
}
$obj=new Sender($number);
That's because you assign a new value to $number in each iteration. Either you need to append to that variable ($number .= $value) or you need to add it to an array ($number[] = $value).

Categories