PHP Append Column to end of the CSV file - php

I have a CSV file in the php server
Want to Add "h3" at the end and fill the row with data "data3"
here is the structure
H1 H2 (h3)
XXX XXX data3
xxx xxx data3
I am trying with the following code for a long time, havent get any luck yet
<?php
$newCsvData = array();
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = 'report_type';
$newCsvData[] = $data;
}
fclose($handle);
}
$handle = fopen('test.csv', 'w');
foreach ($newCsvData as $line) {
fputcsv($handle, $line);
}
fclose($handle);
?>
Please advice

Related

PHP: Remove a row from a CSV if ID occurs multiple times and a column has a specific value

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.

Get string entry from textfile in php

I have a question. How can i get a string from a entry in a textfile.
The texfile looks like:
Blabla2|123456
Blablablabla4|475387638
Blab1|387549900
Now i want to get from Blablablabla4 the number behind the |
Whats the read file function for it?
You can create a custom function, if you need that value often with different keys.
function getValueFromFile($file, $key){
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
if($data[0] == $key){
fclose($handle);
return $data[1];
}
}
fclose($handle);
}
return false;
}
and simply call it like:
echo getValueFromFile("your file name", "Blablablabla4");
Load each line of file to $line and then use function explode('|', $line_variable) for separating a string from int.
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$line = explode('|', $line);
$string = $line[0];
}
fclose($handle);
} else {
// error opening the file.
}

read contents of two csv files in php and merge them into a third file based on a key field

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);
}

How to store each row of the csv file to array in php

I have data in csv file as follows.
Mr,Vinay,H S,Application Engineer,vinay.hs#springpeople.com,99005809800,Yes
Mr,Mahammad,Hussain,Application Engineer,vinay.hs#springpeople.com,99005809800,Yes
I want to store each row in each array.explain me how to do that
I did not understand each row in each array.
use fgetcsv() function to read the CSV file php.
An example
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
OR
If you want to store them in an array you could use
$data = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while(($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = $row;
}
}
Assuming the CSV is a file (if not, make the CSV match the $csv, which is essentially the file broken down in the separate lines), here is a very simple way:
$csv = file('mycsv.csv'); $result = array();
//iterate the lines
foreach ($csv as $line)
// I'd recommend more robust "csv-following" method though (fgetcsv maybe)
$result[] = explode(',',$result);
//show the results
print_r($result);
Though fgetcsv is probably a safer bet (as others have mentioned) (See the docs).
To further extend your comment:
//iterate the lines
foreach ($csv as $line)
// I'd recommend more robust "csv-following" method though (fgetcsv maybe)
$result[] = explode(',',$result);
can become:
//iterate the lines
foreach ($csv as $line)
// combine the current results with the new results
$result = array_marge($result,$line);
or, if order is important:
//iterate the lines
foreach ($csv as $line)
// add each result on to the end of the result array
foreach($line as $val)
// add each value
$result[] = $val;
You can use fgetcsv() for that:
$data = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while(($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = $row;
}
}

How to add columns to CSV using PHP

I need to add columns to an existing csv file ,but i can't find any solution to the problem.I have used "\t" and chr(9) to create columns but no success so please help me by providing me the right solution if any one can
Try this, and have a look at fgetcsv() and fputcsv() in the manual
<?php
$newCsvData = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = 'New Column';
$newCsvData[] = $data;
}
fclose($handle);
}
$handle = fopen('test.csv', 'w');
foreach ($newCsvData as $line) {
fputcsv($handle, $line);
}
fclose($handle);
?>
Could you try using \r\n instead of \n ?

Categories