I'm currently having trouble with reading data from a CSV file. Now it shows the data from the CSV file like this when I print the array.
Array
(
[0] => james;large;33
)
However I want it to have it like this
Array
(
[0] => james
[1] => large
[2] => 33
)
This is the code that I'm using to read data from the CSV file
$file = fopen($file, 'r');
while ($row = fgetcsv($file) ) {
print "<pre>";
print_r($row);
print "</pre>";
}
And this is the CSV file that I'm using:
Any suggestions how I can make this work like I want to? Thanks in advance!
You have different delimiter used in CSV rather default which is ,
fgetcsv
you can define delimiter in fgetcsv function as a second parameter.
$file = fopen($file, 'r');
while ($row = fgetcsv($file, 0, ";") ) {
print "<pre>";
print_r($row);
print "</pre>";
}
Related
I am using fputcsv to write to a CSV from MySQL results:
$list = array("group, variable, value \r\n");
while ($row = mysqli_fetch_assoc($result)) {
array_push($list, $row['strand_pk'] . ',' . $row['unit_name']. "\r\n");
}
$fp = fopen('../reports/data.csv', 'w');
fputcsv($fp, $list);
fclose($fp);
The array when printed on the browser page looks like:
Array
(
[0] => group, variable, value
[1] => 1,Integrated Medical Systems 1
[2] => 1,Integrated Medical Systems 2
[3] => 1,Integrated Medical Practice 1
...
)
The CSV with output looks like:
"group, variable, value
","1,Integrated Medical Systems 1
","1,Integrated Medical Systems 2
","1,Integrated Medical Practice 1
..."
What I need is the CSV to look like:
group,variable,value
1,IMP 3,40
1,IMP 2,8
1,IMP 1,54
1,IMS 2,10
What am I doing wrong here?
fputcsv expects proper, one-dimensional arrays (not comma-separated strings).
Your code should look something like this:
$list = ['group', 'variable', 'value'];
while ($row = mysqli_fetch_assoc($result)) {
$list[] = [$row['strand_pk'], $row['unit_name']]; // you're missing a value here though
}
Then you'll need to loop over the array before writing into the file:
foreach ($list as $row) {
fputcsv($fp, $row);
}
Note that you might not need to build $list at all if you only need to create the CSV with it. Use fputcsv directly within your while loop then.
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
}
?>
I have written a couple pages and some function to turn a .csv file into an array, after which I will be using the array to access and use the data. Most of the code is in place and works but I am stuck with trying to access the fields I want.
The code to create the array looks like this:
//code for accepting and checking the uploaded file
if($ext === 'csv'){
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
set_time_limit(0);
//index
$row = 0;
while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// number of fields in the csv
$num = count($data);
/*echo "<p> $num fields in line $row: <br /></p>\n";*/
// get the values from the csv
$csv[$row]['row1'] = $data[0];
$csv[$row]['row2'] = $data[1];
$csv[$row]['row3'] = $data[2];
$csv[$row]['row4'] = $data[3];
//increment
$row++;
}
print_array($csv[1][0]);
fclose($handle);
}
}
And when I call something like print_array($csv[1]; The result is:
Array
(
[row1] => DataOne
[row1] => DataTwo
[row1] => DataThree
[row1] => DataFour
)
But when I call print_array($csv[1][1]); I get the error: Notice: Undefined Offset: 1 On line *and so on*
Everything I have read makes it seem like this should work. I can't figure out how to get access to what I need. Any help appreciated.
Try to check how many elements your Array have looks to me like it just read the first line and your Array length is 1.
echo("Array count: ".count($csv));
I have created a script that will take a flat text file with 4 bits of information, with commas separating the 4 bits of information, as if it were a csv file, (and I've saved it as such), and it will explode this file into an array, sort the information based on a number (the age of persons), from highest to lowest, and after that I don't have a solution for finishing the script. What I need is to rewrite this array back into the flat file again, now that the information has been properly sorted.
I was thinking either a rewrite or an implode of some kind.
The array looks as such:
Array
(
[0] => Array
(
[name] => john
[age] => 58
[job] => inspector
[salary] => 42000
)
[1] => Array
(
[name] => henry
[age] => 49
[job] => supervisor
[salary] => 38000
)
[2] => Array
(
[name] => monica
[age] => 27
[job] => assistant
[salary] => 29000
)
)
The actual code on my page looks like this:
?php>
$fh = fopen("C:xampp/htdocs/warehouseemplyees.csv", "r");
while(!feof($fh)){
$current = trim(fgets($fh));
$iArray[] = explode(",", $current);
}
$count = count($iArray);
for($x=0;$x<$count;$x++){
$newArray[$x]["name"] = $iArray[$x][0];
$newArray[$x]["age"] = $iArray[$x][1];
$newArray[$x]["job"] = $iArray[$x][2];
$newArray[$x]["salary"] = $iArray[$x][3];
}
function cmp($a, $b)
{
if ($a['age'] == $b['age']) {
return 0;
}
return ($a['age'] > $b['age']) ? -1 : 1;
}
usort($newArray, "cmp");
?>
In the saved flat csv text file, the results look like this:
john,58,inspector,42000
henry,49,supervisor,38000
monica,27,assistant,29000
To conclude. So, once again, I just need to be able to put these results back into the file after this function has sorted them by age highest to lowest. This code works great by the way and the results can be seen in my localhost, but need to get the results back into the file. Thanks for your help.
And please, if you would, be specific with me, I'm very new to programming, and it would help if you told me where to put my specific pieces of information into your code. I can't understand the generic descriptions people often use when talking code. So, if my specific array name goes somewhere or other specific name, please take the time to tell me because I won't know what specific changes to make for my specific application. Please take the necessary pieces from my code above and fill it into your solution so that I'll know. Thanks a bunch!
$fh = fopen("C:xampp/htdocs/warehouseemplyees.csv", "r");
while(!feof($fh)){
$current = trim(fgets($fh));
$iArray[] = explode(",", $current);
}
// You're done reading here
fclose ($fh);
$count = count($iArray);
for($x=0;$x<$count;$x++){
$newArray[$x]["name"] = $iArray[$x][0];
$newArray[$x]["age"] = $iArray[$x][1];
$newArray[$x]["job"] = $iArray[$x][2];
$newArray[$x]["salary"] = $iArray[$x][3];
}
function cmp($a, $b)
{
if ($a['age'] == $b['age']) {
return 0;
}
return ($a['age'] > $b['age']) ? -1 : 1;
}
usort($newArray, "cmp");
// Reopen your file to overwrite with new content : "w". I guess it's the part you were looking for ?
$fh = fopen("C:xampp/htdocs/warehouseemplyees.csv", "w");
foreach ($newArray as $line) {
fputcsv ($fh, $line);
}
fclose ($fh);
You might want to give a look at fputcsv to understand the reading part, then read about fgetcsv to understand how you could have designed your reading part easily.
http://php.net/manual/en/function.fputcsv.php
http://php.net/manual/en/function.fgetcsv.php
In CakePHP, with the following code i am trying to Export users email in CSV.
I am getting Errors.
Code Refrence site
Error:
Notice (8): Undefined offset: 0 [APP\View\Frontusers\admin_exportemails.ctp, line 12]
Warning (2): fputcsv() expects parameter 2 to be array, null given [APP\View\Helper\CsvHelper.php, line 36]
Notice (8): Undefined offset: 1 [APP\View\Frontusers\admin_exportemails.ctp, line 12]
Warning (2): fputcsv() expects parameter 2 to be array, null given [APP\View\Helper\CsvHelper.php, line 36]
admin_exportemails.ctp
$line= $useremails[0]['Frontuser'];
$this->CSV->addRow(array_keys($line));
foreach ($useremails as $key => $useremail)
{
$line =$useremail[$key]['Frontuser'];
$this->CSV->addRow($line);
}
$filename='useremails';
echo $this->CSV->render($filename);
You're messing up your foreach. You split it up in the $key and the $useremail sub-array, which is OK. But then you iterate over it and try to access $useremail[$key]['Frontuser'] again, which is nonexistent at that point.
foreach ($useremails as $key => $useremail)
This causes the [0] and [1] in the original $useremails array to be set as $key, but you iterate over all the items over the $useremails, so you can simply:
$line = $useremail['Frontuser'];
You don't need the $key, since that's not part of the iterated item, e.g. the first time your foreach runs, it sees this:
[Frontuser] => Array
(
[name] => Rash
[email] => rash.com
)
And on the second iteration it sees this:
[Frontuser] => Array
(
[name] => John
[email] => john#gmail.com
)
So there is no [0] or [1] index anymore.
$useremail[$key]['Frontuser'];
should be
$useremail['Frontuser'];
Actually there's no need for your code to include the key in the foreach loop at all.
That's PHP 101, so for further information please refer to the manual: http://php.net/foreach
You can simply pass your data array in that function and your csv generated in webroot folder.
Note:- 1. You should put blank csv file at webroot folder.
2. you should store all information in a sub array which contain only values not Model index.
function generate_csv($data_array=array()){
// pr($data_array);die;
foreach ($data_array as $key => $value) {
$newdata[] = $key.','.$value;
}
// pr($newdata);die;
$f = fopen(APP.'webroot/csv_file.csv', 'w+');
foreach ($newdata as $line) {
fputcsv($f, array($line), ',');
}
fseek($f, 0);
fclose($f);
}
you made mistake in the for loop and iterated it in wrong way.just ommit the below line from the foreach loop.
$line =$useremail[$key]['Frontuser'];
Here have tow options
1. save csv file in folder not sent output to browser and
2. send output to browser
function generate_csv($data_array = array()) {
//$f = fopen(APP . 'webroot/files/unsaved_bars.csv', 'w+'); // for save csv file in folder not sent output to browser
$f = fopen("php://output", "a"); // for send output to browser
$headers[] = array('id','name','other_info'); // for header row
$data_array = array_merge($headers, $data_array);
foreach ($data_array as $line) {
fputcsv($f, $line, ',');
}
//fseek($f, 0);
fclose($f);
}