I want to store csv columns data into array
I have did this so far.
$csvfile = file('testfile.csv');
$csvData = [];
foreach ($csvfile as $key => $line) {
$csvData[] = str_getcsv($line);
}
This works fine but the first line also include in array
I want to skip first line
Remove the first element of the array with array_shift().
$csvfile = file('testfile.csv');
array_shift($csvfile);
$csvData = array_map('str_getcsv', $csvfile);
or you can do like this
$csvfile = file('testfile.csv');
unset($csvfile[0]);
$csvData = [];
foreach ($csvfile as $key => $line) {
$csvData[] = str_getcsv($line);
}
Related
I want to write $totalToday data from API to csv file. If current date not existed, append new record for current date. I've came with following solution.
$search = date("d/m/Y");
$lines = file('data.csv');
$line_number = false;
foreach($lines as $key => $line) {
$line_number = (strpos($line, $search) !== FALSE);
}
if(!$line_number){
$entry = array(date("d/m/Y"), $totalToday);
$fp = fopen('data.csv', 'a');
fputcsv($fp, $entry);
fclose($fp);
}
My problem is $totalToday from API get updated time to time. I want to record the latest update. so I replaced $search = date("d/m/Y"); with $search = date("d/m/Y"), $totalToday now I have multiple record for same date in my data.csv. I want to overwrite the current date record with very latest data without append to new line. How to accomplish my requirement
Example data: (first rows)
date,newCases,totalToday
13/04/2020,21,110
14/04/2020,26,125
14/04/2020,30,130
I want to replace 14/04/2020,26,125 with 14/04/2020,30,130
One approach could be this:
<?php
$search = '14/04/2020';
$other_data_from_api = array(188,102);
$lines = file('data.csv');
//Create a new array and set all dates as keys
//The latest set key would be the current
$new_arr = array();
foreach($lines as $line) {
$exp = explode(',', $line);
$new_arr[$exp[0]] = array($exp[1], $exp[2]);
}
/*
So in your example:
13/04/2020,21,110
14/04/2020,26,125
14/04/2020,30,130
the array $new_arr would contain:
[13/04/2020] => Array
(
[0] => 21
[1] => 110
)
[14/04/2020] => Array
(
[0] => 30
[1] => 130
)
*/
//Rewrite the whole file with values from this new array
$fp = fopen('data.csv', 'w');
foreach($new_arr as $key=>$line) {
$entry = $key . ',' . implode(',', $line);
fputs($fp, $entry);
}
fclose($fp);
You could also:
//Rewrite the whole file with values from this new array
//And include the actual data from the API
//(Then 188,102 would be included with the data of the $search variable)
$fp = fopen('data.csv', 'w');
foreach($new_arr as $key=>$line) {
if ($search == $key) {
$entry = $search . ',' . implode(',', $other_data_from_api);
}
else {
$entry = $key . ',' . implode(',', $line);
}
fputs($fp, $entry);
}
fclose($fp);
I am using PHP and converting the JSON data into the CSV format and later on read the same CSV file for further processing.
Below is my code that converts the JSON data in to the CSV format.
function LoadDataFromFile($file)
{
$json = file_get_contents($file);
$array = json_decode($json, true);
$f = fopen('out.csv', 'w');
$firstLineKeys = false;
$keys = array();
//first collect keys
foreach($array as $line){
foreach($line as $key => $value){
if(!in_array($key, $keys))
$keys[] = $key;
}
}
$keyString = implode(",", $keys);
fwrite($f, "$keyString\n");
foreach ($array as $line)
{
$outputArray = array();
foreach($keys as $key){
if(array_key_exists($key, $line)){
$outputArray[] = str_replace(',', '', $line[$key]);;
} else {
$outputArray[] = "";
}
}
$outputString = implode(",", $outputArray);
fwrite($f, "$outputString\n");
}
fclose($f);
}
As we can see that, i am writing data into the "out.csv" file, and later on i am reading same CSV file and assign the value/ full contents of the same file line by line to $array variable, as shown below.
$array = explode("\n", file_get_contents('out.csv'));
Now, I want to directly assign the value of csv contents into the $array variable with out using the intermediate "out.csv" file.
Wondering what data structure should i use while converting JSON data to CSV format, and possible code changes required for "LoadDataFromFile" method?
If you can already convert the json into csv, then just append the output strings together assigned to a string variable instead of writing it to a file. Or am I misunderstanding what you want?
Instead of:
fwrite($f, "$outputString\n");
you can put:
$csv .= $outputString;
And finish it with:
$array = explode("\n", $csv);
I have multiple arrays, where I want to name each array at the end of the for each loop.
The code php code:
<?php
$csv = array_map("str_getcsv", file("translations/dk.csv"));
foreach ($csv as $line){
if ($line[1] != NULL){
$line[0] = $line[1];
}
print_r($line[0]);
print_r("<br />");
}
fclose($csv);
?>
Example of the arrays.
Array ( [0] => Search and Save [1] => Søg og Spar på Hoteller )
Array ( [0] => Where are you going? [1] => Hvor skal du hen? )
Now the output of line[0] is each time the foreach loop runs naturally with a different value. But I need to name each $line[0] on every loop so I can access them afterwards. How do I do this ?
First of all, you shouldn't use file() to split up the lines; CSV records may span multiple lines.
$f = fopen("translations/dk.csv", 'rt');
$csv = array();
while (($data = fgetcsv($f)) !== false) {
$csv[] = $data;
}
fclose($f);
Second, to select the first column from the array you can use array_column():
$results = array_column($csv, 0);
// "Search and Save", "Where are you going?"]
Maybe you're looking for something like this:
<?php
$csv = array_map("str_getcsv", file("translations/dk.csv"));
$results = array();
foreach ($csv as $k => $line){
if ($line[1] != NULL){
$line[0] = $line[1];
$results[$k] = $line[0];
}
print_r($line[0]);
print_r("<br />");
}
print_r($results);
?>
Consider a txt file of a list of items
qqqqqq
eeeeee
dddddd
hhhhhh
dddddd
hhhhhh
999999
And some of the items in the list are duplicates. how do I output a using php a text file where anything that is duplicated is removed.
the result:
qqqqqq
eeeeee
999999
You can use array_unique
and then right the content back
$file = fopen("filename.txt", "r");
$members = array();
while (!feof($file)) {
$members[] = fgets($file);
}
fclose($file);
$unique_members = array();
$unique_members = array_unique($members);
var_dump($unique_members);
//write the content back to the file
The above solution was for removing the duplicates only and make them unique. Thanks to nhahtdh for pointing it out.
$count_members = array_count_values($members);
foreach($count_members as $key=>$value)
{
if($value == 1)
//write it to the file
}
So you will not need the array_unique stuff
Sorry again
<?php
$file = file_get_contents('file.txt'); //get file to string
$row_array = explode("\n",$file); //cut string to rows by new line
$row_array = array_count_values(array_filter($row_array));
foreach ($row_array as $key=>$counts) {
if ($counts==1)
$no_duplicates[] = $key;
}
//do what You want
echo '<pre>';
print_r($no_duplicates);
file_put_contents('no_duplicates.txt',$no_duplicates); //write to file. If file don't exist. Create it.
I am new to PHP and would like to be able to read in a csv file which has two columns, one is the number (kind of like a ID) then the other holds a integer value. I have looked up the fgetcsv function but I have not been able to find a way to read a specific column from the csv file.
I would like to get all the values from the second column only, without the heading.
Any way of doing this?
This is what I have so far:
$file = fopen('data.csv', 'r');
$line = fgetcsv($file);
And this is some sample data from the csv file:
ID,Value
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00
Any help would be appreciated.
Thanks.
fgetcsv() only reads a single line of the file at a time. You'll have to read the file in a loop to get it all:
$data = array();
while($row = fgetcsv($file)) {
$data[] = $row;
}
The heading you can skip by doing an fgetcsv once outside the loop, to read/trash the header values. And if you only want the second column, you can do:
$data[] = $row[1];
However, since you've got data in there, maybe it might be useful to keep it, plus key your new array with the ID values in the csv, so you could also have:
$data[$row[0]] = $row[1];
and then your nice shiny new array will pretty much exactly match what's in the csv, but as an array keyed by the ID field.
$csv = array_map("str_getcsv", file("data.csv", "r"));
$header = array_shift($csv);
// Seperate the header from data
$col = array_search("Value", $header);
foreach ($csv as $row) {
$array[] = $row[$col];
}
// Iterate through data set, creating array from Value column
$header = fgetcsv($h);
$rows = array();
while ($row = fgetcsv($h)) {
$rows []= array_combine($header, $row);
}
$fp = fopen($filePath, "r+");
$header = fgetcsv($fp);
while ($members = fgetcsv($fp)) {
$i = 0;
foreach ($members as $mem) {
$membersArray[ $i ][ ] = $mem;
$i++;
}
}
$newArray = array_combine($header, array_map("array_filter",$membersArray));
You can also use this class http://code.google.com/p/php-csv-parser/
<?php
require_once 'File/CSV/DataSource.php';
$csv = new File_CSV_DataSource;
$csv->load('data.csv');
var_export($csv->connect());
?>