How to fetch specific column from a file? - php

I am trying to fetch a specific column from a file by using PHP. but so far I got all of it, have no idea how to do this, I can not find any information online so if anyone could help me about this , I will be very appreciated. The data in file is like blow:
20110101,1110.0
20110102,1100.0
20110103,50.0
20110104,6355.0
........
I just want to fetch the second column, here is my PHP code:
$file_handle = fopen("file_name", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
echo $line."<br/>";
}
fclose($file_handle);

Have you tried this (which actually does what you want, without refactoring) :
$file_handle = fopen("file_name", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$cols = explode(',', $line);
echo $cols[1]."<br/>";
}
fclose($file_handle);
??

As Vlad says, use fgetcsv.
// adapted from PHP example
$max_row_len = 1000;
if (($file_handle = fopen("file_name", "r")) !== FALSE) {
while (($data = fgetcsv($file_handle, $max_row_len, ",")) !== FALSE) {
echo $data[1]."<br/>";
}
fclose($file_handle);
}

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.

Saving specific columns of CSV to another CSV file in PHP

so trying to read a csv file and extracting details from the file and wish to store specific columns of the csv to another csv file.
I have managed to extract the specific columns of the input csv file but not really sure how I can write those extracted columns to another csv file.
Here is the part of my work:
$row = 1;
if (($handle = fopen("testtable.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo $data[0] . "\n" . $data[1] . "<br />\n";
}
$file = fopen("editedTable.csv","w");
foreach ( $data as $line) { //working on this part of the code
fputcsv($file, explode(',',$line));
}
fclose($handle);
}
Obviously there is an error in the foreach loop as I am trying to work out the logic.
The data that is extracted is basically first and the second column (data[0], data[1]). Just need this to write to another CSV file. The input csv is just a comma delimited file with 5 columns. Any idea how I can modify the foreach loop and the use the fputcsv method?
Thanks
fputcsv accepts an array on the second parameter.
I think this is what you looking for:
<?php
$file = fopen("editedTable.csv","w");
$row = 1;
if (($handle = fopen("testtable.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000)) !== FALSE) {
$num = count($data);
$row++;
echo $data[0] . "\n" . $data[1] . "<br />\n";
fputcsv($file, [$data[0], $data[1]]);
}
}
fclose($handle);
fclose($file);
Because you place the fputs outside of the $data initial loop, you catch only one row, here is the modified code.
$row = 1;
$file = fopen("editedTable.csv","w");
if (($handle = fopen("testtable.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo $data[0] . "\n" . $data[1] . "<br />\n";
$line = $data[0].", ".$data[1];
$line .= "\n";
fputs($file, $line);
}
fclose($handle);
}
fclose($file);

How to do category mapping from csv?

I have a csv form which I have to make the category mapping. I had let this csv read from controller.And, I am trying to establish a hierarchy .So, that I can map . But , I am not able to do that. Please help!
[link:https://pricefalls.zendesk.com/hc/en-us/articles/204287645-How-do-I-create-a-category-map- “Pricefalls Category Taxonomy”].My csv has the same pattern as shown in the given link.
public function actionReadcsv()
{
$row = 1;
$csvFile = Yii::getAlias('#frontend') . '/modules/pricefalls /csv/Pricefalls_Categories1.csv';
if (($handle = fopen($csvFile, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
$row++;
$create_category[] =$data;
}
Pricefallscategories::categorytree($create_category);
echo "<pre>";
print_r($create_category);
echo"</pre>";
fclose($handle);
}
}

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.
}

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