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);
Related
I've got a csv file which contains product datas and prices from two distributors.
There are 67 keys in this file.
Now I want to search all EANs in this file which are twice available and then get the cheapest price.
After that delete the other higher price product line.
The CSV has a key for my merchant.
I made a test csv for easier view:
artno;name;ean;price;merchant
1;ipad;1654213154;499.00;merchant1
809;ipad;1654213154;439.00;merchant2
23;iphone;16777713154;899.00;merchant2
90;iphone;16777713154;799.00;merchant1
After the script runs through, the csv should look like (writing to new file):
artno;name;ean;price;merchant
809;ipad;1654213154;439.00;merchant2
90;iphone;16777713154;799.00;merchant1
I played around with fgetcsv, looping through the csv is not a problem, but how I can search for the ean in key 2?
$filename = './test.csv';
$file = fopen($filename, 'r');
$fileline = 1;
while (($data = fgetcsv($file, 0, ";")) !== FALSE) {
if($fileline == "1"){ $fileline++; continue; }
$search = $data[2];
$lines = file('./test.csv');
$line_number = false;
$count = 0;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE) ? $key : $line_number;
$count++;
}
if($count > 2){
echo "<pre>",print_r(str_getcsv($lines[$line_number], ";")),"</pre>";
}
}
I think this is what you are looking for:
<?php
$filename = './test.csv';
$file = fopen($filename, 'r');
$lines = file('./test.csv');
$headerArr = str_getcsv($lines[0], ";");
$finalrawData = [];
$cheapeastPriceByProduct = [];
$dataCounter = 0;
while (($data = fgetcsv($file, 0, ";")) !== FALSE) {
if($dataCounter > 0) {
$raw = str_getcsv($lines[$dataCounter], ";");
$tempArr = [];
foreach( $raw as $key => $val) {
$tempArr[$headerArr[$key]] = $val;
}
$finalrawData[] = $tempArr;
}
$dataCounter++;
}
foreach($finalrawData as $idx => $dataRow ) {
if(!isset($cheapeastPriceByProduct[$dataRow['name']])) {
$cheapeastPriceByProduct[$dataRow['name']] = $dataRow;
}
else {
if(((int)$dataRow['price'])< ((int)$cheapeastPriceByProduct[$dataRow['name']]['price'])) {
$cheapeastPriceByProduct[$dataRow['name']] = $dataRow;
}
}
}
echo "<pre>";
print_r($finalrawData);
print_r($cheapeastPriceByProduct);
I just added $finalData data array to store the parsed data and associated all rows with their header key counterpart then you can compare and filter data based on your criteria.
I have a multidimensional array $arrResult1 imported from CSV file, I want to replace the multiple values in that array with different values. I have tried str_replace and it works for single replacement.
<?php
$File = 'charge1.csv';
$arrResult = array();
$handle = fopen($File,"r");
if(empty($handle) == false){
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){
$arrResult[] = $data;
}
fclose($handle);
}
$file = 'ActualCharge.csv';
$arrResult1 = array();
$handle = fopen($file,"r");
if(empty($handle) == false){
while(($values = fgetcsv($handle, 1000, ",")) !== FALSE){
$arrResult1[] = $values;
}
fclose($handle);
}
$newArray = array();
foreach($arrResult1 as $inner_array) {
$newArray[] = str_replace("$11.16","$14.00", $inner_array);
}
var_dump($newArray[6]);
But when I try to replace more values like this
$newArray[] = str_replace(array("$11.16","$14.00"),array("$12.16","$15.00"), $inner_array);
It does not work. I have total 16 values that need to be replaced. Can you please help and let me know what I am doing wrong here or if there is any other way to solve this. TIA
here are the links to both csv files
https://drive.google.com/open?id=15JXhljASiDaZAyF0I6vC5_vfvFWH5Ylo
https://drive.google.com/open?id=1XzbzE39sCVVi4Ox1uj36g0smZJ4X4kCv
I would like to create a JSON file with my CSV file.
But I get an error with the function array_combine.
How could i fix that please?
Here is the code:
function csvtojson($file,$delimiter)
{
if (($handle = fopen($file, "r")) === false)
{
die("can't open the file.");
}
$csv_headers = fgetcsv($handle, 4000, $delimiter);
$csv_json = array();
while ($row = fgetcsv($handle, 4000, $delimiter))
{
$csv_json[] = array_combine($csv_headers, $row);
}
fclose($handle);
return json_encode($csv_json);}
Here is the error:
Warning: array_combine(): Both parameters should have an equal number
of elements in /var/www/inae-obs/app/controllers/csvToJson.php on line
15
You can use a custom array_combine method to overcome this:
<?php
function array_combine_custom($keys, $values){
$combined = [];
$keys_values = array_values($keys);
$values_values = array_values($keys);
foreach($keys_values as $index => $key){
$combined[$key] = isset($values_values[$index]) ? $values_values[$index] : null;
}
return $combined;
}
if the keys and values are in order and you are OK with ignoring the rest.
I have an array of csv elements and I want to retrieve the key of the column 'Due Date' (the result is 10) and display the array at the column 10. However, it doesn't display the result but it will show the column 1 and I don't know why.
Code:
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
$value = array_search('Due Date', $line);
print_r($line[$value]);
}
Just do it like this so you can easily get the column number 10:
$var = array();
while($row = fgetcsv($yourFile)) {
$var[] = $row;
}
//Get Column 10
$var[] = $row[9];
Edit:
<?php
$valueOfSearch = "YOUR VALUE OF SEARCH";
$linesOfCsv = file('YOUR PATH.csv');
$lineNumberOfCSV = false;
while (list($key, $line) = each($linesOfCsv) and !$lineNumberOfCSV) {
$lineNumberOfCSV = (strpos($line, $valueOfSearch) !== FALSE);
}
if($lineNumberOfCSV){
//Add YOUR CONDITION
}
?>
Open the fine and take csv values inside an array and close the file. After that try your logic.
So to get value you can use:
$file = 'file.csv';
$line = array();
$file = fopen($file,"r");
while(! feof($file))
{
$line = fgetcsv($file);
}
fclose($file);
$key = array_search('Due Date', $line);
print_r($line[$key]);
I would like to convert a CSV to Json, use the header row as a key, and each line as object. How do I go about doing this?
----------------------------------CSV---------------------------------
InvKey,DocNum,CardCode
11704,1611704,BENV1072
11703,1611703,BENV1073
---------------------------------PHP-----------------------------------
if (($handle = fopen('upload/BEN-new.csv'. '', "r")) !== FALSE) {
while (($row_array = fgetcsv($handle, 1024, ","))) {
while ($val != '') {
foreach ($row_array as $key => $val) {
$row_array[] = $val;
}
}
$complete[] = $row_array;
}
fclose($handle);
}
echo json_encode($complete);
Just read the first line separately and merge it into every row:
if (($handle = fopen('upload/BEN-new.csv', 'r')) === false) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$complete = array();
while ($row = fgetcsv($handle, 1024, ',')) {
$complete[] = array_combine($headers, $row);
}
fclose($handle);
echo json_encode($complete);
I find myself converting csv strings to arrays or objects every few months.
I created a class because I'm lazy and dont like copy/pasting code.
This class will convert a csv string to custom class objects:
Convert csv string to arrays or objects in PHP
$feed="https://gist.githubusercontent.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194/raw/ec46f6c2017325345e7df2483d8829231049bce8/data.csv";
//Read the csv and return as array
$data = array_map('str_getcsv', file($feed));
//Get the first raw as the key
$keys = array_shift($data);
//Add label to each value
$newArray = array_map(function($values) use ($keys){
return array_combine($keys, $values);
}, $data);
// Print it out as JSON
header('Content-Type: application/json');
echo json_encode($newArray);
Main gist:
https://gist.github.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194
For those who'd like things spelled out a little more + some room to further parse any row / column without additional loops:
function csv_to_json_byheader($filename){
$json = array();
if (($handle = fopen($filename, "r")) !== FALSE) {
$rownum = 0;
$header = array();
while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {
if ($rownum === 0) {
for($i=0; $i < count($row); $i++){
// maybe you want to strip special characters or merge duplicate columns here?
$header[$i] = trim($row[$i]);
}
} else {
if (count($row) === count($header)) {
$rowJson = array();
foreach($header as $i=>$head) {
// maybe handle special row/cell parsing here, per column header
$rowJson[$head] = $row[$i];
}
array_push($json, $rowJson);
}
}
$rownum++;
}
fclose($handle);
}
return $json;
}