I want to edit the first line (column titles) of an CSV file. Only one problem, the script I have is replacing everything. I've tried to search for a solution, but no luck.
Script:
<?php if(isset($_FILES["file"]["tmp_name"])){
$newCsvData = array();
if (($handle = fopen("".$_FILES["file"]["tmp_name"]."", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $base = array("EAN","article","status");
$replacements = array(1=> "SKU");
$basket = array_replace($base, $replacements);
$newCsvData[] = $basket;
}
fclose($handle);
}
$handle = fopen("export/".$_FILES["file"]["name"]."", "w");
foreach ($newCsvData as $line) {
fputcsv($handle, $line);
}
fclose($handle); } else{ echo" ";} ?>
Does someone know what I'm doing wrong?
You should try:
$first = true;
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$base = array("EAN", "article", "status");
$replacements = array(1 => "SKU");
if($first){
$data = array_replace($base, $replacements);
$first = false;
}
$newCsvData[] = $data;
}
$first is a flag to detect just first row and replacing $data array values with titles array. Then you should push $data to $newCsvData. So only first row will replace by new values and other rows will remain as same data.
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 data as below in a CSV file. The green lines are what I'd like to keep.
Basically if someone has a single line, I want to keep it.
If they have multiple lines, I want to remove any where the 3rd column is A - Fully Fit.
After running through the whole file, I then want to save it over the original.
I tried writing the code but not sure if it's a Friday but the logic is escaping me at the moment.
There could be just a single line or there could be dozens. So if an ID has 1000 rows, I would just want to delete the rows for that ID where the 4th column is "A - Fully Fit"
UPDATE
This code works but not sure if it's the most optimal
// DECLARE ARRAYS
$a = Array();
$b = Array();
$c = Array();
// LOOP THROUGH FILE AND COLLECT DUPLICATES
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($line = fgetcsv($handle, 4096, ",")) !== FALSE) {
$a[$line[1]][] = 'SHAKKA';
}
foreach ($a as $k=>$v) {
if (count($v)>1) {
$b[] = $k;
}
}
}
// IF A DUPLICATE THEN REMOVE ROWS THAT ARE 'A - Fully Fit'
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($golly = fgetcsv($handle, 4096, ",")) !== FALSE) {
if (in_array($golly[1],$b) && $golly[3] == 'A - Fully Fit') {
}
else {
$c[] = $golly;
}
}
}
fclose($handle);
// WRITE THE FILE
$fp = fopen($filename, 'wa+');
foreach ($c as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
<?php
if (($handle = fopen($filename, "r")) !== FALSE) {
$new_rows = [];
$hash_ids = [];
while (($line = fgetcsv($handle, 4096, ",")) !== FALSE) {
if($line[3] === 'A - Fully Fit'){
if(isset($hash_ids[$line[1]])) continue;
$hash_ids[$line[1]] = true;
}
$new_rows[] = $line;
}
fclose($handle);
// WRITE TO THE FILE
$fp = fopen($filename, 'wa+');
foreach ($new_rows as $current_row) {
fputcsv($fp,$current_row);
}
fclose($fp);
}
In the above code, we maintain a hash(associative array) for each ID. If we have already come across with an ID with A - Fully Fit, then we skip the row, else we add it to the list.
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'm loading a CSV file and looping over each line. I want to assign variables to each column (shown in the list line), then in the first instance, show each lines $project data. So essentially that will give me each project code per line.
I'll be using the other variables but just want this one working for now.
There should be 1000 projects but it's only showing one, where am I going wrong?
<?php
$row = 1;
if (($handle = fopen("users.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, ",")) !== FALSE) {
$num = count($data);
$row++;
list($project, $rod, $rom, $asm, $contract, $site, $town, $postcode, $country) = $data;
echo $contract;
}
fclose($handle);
}
?>
in the while, just use
$project = $data[0];
Each time you call fgetcsv in your while statement, this reads the next line from the csv file. So you can either use...
<?php
if (($handle = fopen("users.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {
list($project, $rod, $rom, $asm, $contract, $site, $town, $postcode, $country) = $data;
echo $project.PHP_EOL;
}
fclose($handle);
}
?>
Or to get a list of the projects...
<?php
if (($handle = fopen("users.csv", "r")) !== FALSE) {
$projects = [];
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {
list($project, $rod, $rom, $asm, $contract, $site, $town, $postcode, $country) = $data;
$projects[] = $project;
}
fclose($handle);
print_r($projects);
}
?>
I've searched the web and looked through existing answers but cant find a solution to this one. I want to use php to do the following task. Here are my files:
csv file 1: member.csv
member1|john|smith|2009
member2|adam|jones|2007
member3|susie|rose|2002
csv file 2: classes.csv
member1|massage|swimming|weights
member2|gym|track|pilates
member3|yoga|running|stretches
I want to output a third file called file3.csv which merges the two above files together based on the key field which is the member number. the output should be like this:
member1|john|smith|2009|massage|swimming|weights
member2|adam|jones|2007|gym|track|pilates
member3|susie|rose|2002|yoga|running|stretches
the delimiter is a bar character. I want to do this just using php - no other languages.
I would be very greatful for a solution.
Matt
Read both files and store data to the array with keys: member1, ...
Write a new file lines in loop:
foreach ($firstArray as $key => $value1) {
$value2 = $secondArray[$key];
// ...
}
<?php
$data = array();
if (($handle = fopen('file1.csv', 'r')) !== FALSE) {
while (($line = fgetcsv($handle, 0, '|')) !== FALSE) {
$memberId = $line[0];
unset($line[0]);
$data[$memberId] = $line;
}
fclose($handle);
}
if (($handle = fopen('file2.csv', 'r')) !== FALSE) {
while (($line = fgetcsv($handle, 0, '|')) !== FALSE) {
$memberId = $line[0];
unset($line[0]);
$data[$memberId] = array_merge($data[$memberId], $line);
}
fclose($handle);
}
ksort($data); // not needed, but puts records in order by member
if (($handle = fopen('file3.csv', 'w')) !== FALSE) {
foreach($data as $key => $value) {
fwrite($handle, "$key|" . implode('|', $value) . "\n");
}
fclose($handle);
}
Try this. It is untested.
$arr_one = array();
if (($fp = fopen("member.csv", "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$arr_one[$data[0]] = $data;
}
fclose($fp);
}
$arr_two = array();
if (($fp = fopen("classes.csv", "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$arr_two[$data[0]] = $data;
}
fclose($fp);
}
$classes_field_count = sizeof(current($arr_two));
$members = array_keys($arr_one);
foreach ($members as $key) {
if (!isset($arr_two[$key])) {
$arr_two[$key] = range(0, ($classes_field_count - 1));
}
unset($arr_two[$key][0]);
$result_arr[$key] = array_merge($arr_one[$key], $arr_two[$key]);
}
if (($fp = fopen("file3.csv", "w")) !== FALSE) {
foreach ($result_arr as $fields) {
fputcsv($fp, $fields, '|');
}
fclose($fp);
}