Using PHP to search CSV by Column? - php

Having trouble searching CSV file by Column. For example, I have the following CSV file:
NAME, HAS AN IPHONE, HAS ANDROID
bob, yes, no,
fred, no, yes,
How could I search column 2 for a 'yes' value using php,
then return only the rows with "yes" in second column results?

I think, This can help you. Read about fgetcsv
<?php
$result = [];
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($data[1] == 'yes') //Checks second column is 'yes'
array_push($result, $data);
}
fclose($handle);
var_dump($result);
}
?>

Assuming you have already parsed the csv file into an array.
The second parameter of array_keys function is mixed $search_value
If specified, then only keys containing these values are returned.
To search a specific column, use array_column:
$res = array_keys(array_column($csv, 1), "yes");
See test at eval.in; This would return keys of of all "yes" matches in the second column.

Have you tried anything if so please post that also, you may find this helpful
$csv = array_map('str_getcsv', file('data.csv'));
foreach($csv as $line){
if($line[1] == 'yes'){
//do what ever you want
echo "found yes";
}
}

Well this is what i tried and it worked for searching for a value in rows.
Then you can get the values of the rows and use it.
<?php
$file = fopen("test.csv", "r");
$str = "n#gmail.com";
while (($data = fgetcsv($file)) !== false)
{
if(in_array($str, $data))
{
foreach ($data as $i)
{
echo $i."<br>";
}
}
}
fclose($file);
?>

Related

I am trying to make a search bar in php to search search my csv file. However, I am not able to retrieve anything

I am trying to retrieve a row from my csv file.
For example:
//my csv file
Serial No., Name, Type, Category
12345, John, SG, Old
23456, Mary, MY, New
I am trying searching by serial number. What I want to achieve is something like this.
search: 12345
results: 12345, John, SG, Old
I tried using the method below
<?php
//from the previous page of my search bar
$sn = $_POST["sn"];
$result = [];
if (($handle = fopen("gameDirectory.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($data[1] == $sn)
print_r($data);
}
fclose($handle);
}
?>
It is not showing anything after i click search.
An array always start at 0.
Change $data[1] to $data[0].
Better code will nomalize both variable, somthing like :
<?php
//from the previous page of my search bar
$sn = intval($_POST["sn"]);
$result = [];
if (($handle = fopen("gameDirectory.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if(intval($data[0]) == $sn)
print_r($data);
}
fclose($handle);
}

Retrieve multiple lines within same cell from CSV file

I am trying to retrieve some data from CSV file. I used the following code to go through CSV:
//create array for csv file
$array_data = array();
$row = 0;
if (($handle = fopen("import/pdf_data.csv", "r")) !== FALSE) {
// read the CSV from root folder "web/interval/import"
while (($data = fgetcsv($handle, 0, ";")) !== FALSE) {
if ($row > 0) {
$array_data[$row] = $data;
}
$row++;
}
fclose($handle);
}
//loop through all the feature data array
foreach ($array_data as $entry_value => $array_column) {
foreach( $array_column as $value )
{
//split data
list($col1,$col2,$col3) = explode( ',', $value );
echo "Name: ".$col1.", Surname: ".$col2.", Text: ".$col3."<br/>";
When I print the columns... col1 and col2 are fine as they have only one single value in their cells. col3 may contain multiple lines. Let's say for example (see below one cell of col3):
col3
::::::::::::::
Text-a in line 1
Text-a in line 2
Text-a in line 3
If there are multiple lines within one cell then the CSV output will be like this:
"Text-a in line 1Text-a in line 2Text-a in line 3"
and with the code I use above it prints the first line
"Text-a in line 1
then in a new entry the second line etc etc.
What I want to achieve is the following format
echo "Name: ".$col1.", Surname: ".$col2.", Text: ".$col3."<br/>";
Which doesn't work with multiple lines as I get this:
Name: Test, Surname: Test2, Text: "Text-a in line 1
Name: , Surname: , Text: Text-a in line 2
Any suggestions would be much appreciated, thank you
A CSV file may contain multi-line value in a cell. But it needs to be enclosed in quotes. Excel does this correctly - create a test file and save into CSV. PHP function fgetcsv also can read such files correctly.
Example file:
"col1","col2","col3"
"test1","test2.1
test2.2
test2.3","test3"
The second column in the second row contains multi-line value and this is a perfectly valid CSV file.
Here is the correct code:
$array_data = array();
$row = 0;
if (($handle = fopen("import/pdf_data.csv", "r")) !== FALSE) {
// read the CSV from root folder "web/interval/import"
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if ($row > 0) {
$array_data[$row] = $data;
}
$row++;
}
fclose($handle);
}
//loop through all the feature data array
foreach ($array_data as $row) {
list($col1,$col2,$col3) = $row;
echo "Name: ".$col1.", Surname: ".$col2.", Text: ".$col3."<br/>";
}
I could advice you by another simple solution. It is using fgets() and explode()
$handle = fopen("inputfile.txt", "r");
$out = array();
if ($handle) {
while (($line = fgets($handle)) !== false) {
$arr = explode(',' $line);
$out[] = trim($arr[2]); // Supposing you want to get the third cell.
}
fclose($handle);
} else {
// error opening the file.
}
print_r($out);
Reference: How to read a file line by line in php

PHP use the fputcsv CSV to write same data in column for each row

I am trying to put a new data "exemple" for each line of the CSV. The lines of the csv varies. The header column name would be ExempleRow
There is not separator only a delimiter which is the semi colon.
I'm using fputcsv, it must have an array to fill the csv file with desired data. But in my case the number of lines changes for each csv.
So far it adds the new column with but I can't understand how to put the same value in each line for that column ?
<?php
$newCsvData = array(); // here should I specify the same data value "exemple data" for each line ? but how ?
if (($handle = fopen("exemple.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 9999, ";")) !== FALSE) {
$data[] = 'ExempleRow';
$newCsvData[] = $data;
}
fclose($handle);
}
$handle = fopen('exemple.csv', 'w');
foreach ($newCsvData as $line) {
fputcsv($handle, $line,';',' ');
}
fclose($handle);
?>
If you want to show the keys of the array as the first column then you can do this. If you dont have an associative array or you want to hard code the column headers for what ever reason you can simply change the array_keys($line) for a hard coded array.
$handle = fopen('exemple.csv', 'w');
$keys = false;
foreach ($newCsvData as $line) {
if ($keys === false) {
//$header = array('HeaderOne', 'HeaderTwo', 'HeaderThree', 'HeaderFour'); Use this if you want to hard code your headers
fputcsv($handle, array_keys($line), ';', '');
$keys = true;
}
fputcsv($handle, $line,';',' ');
}
fclose($handle);

How do I get only the second column of a CSV file using PHP?

I have the csv file(test.csv) and have the text as below:
1,maly,maly(),f,df
2,cheata,aaa,df,df
3,cheata,df,df,df
4,maly,fc,cfv,f
5,maly,df,fg,fg
6,chantha,fc,gf,fg
7,chantha,gh,a,g
8,David,fgfd,dfg,g
What I want:
I want to diplay only:maly cheata chantha David.For the name that have two or more the same,take only one.And I have the php code as below:
$c=0;
$data=fopen('test.csv','r');
while($row=fgets($data)){
if($c!=0){
echo $row[3]."<br>\n";
}
$c++;
}
The problem is
It does not display what I want. It displays
h h a a h h a
How do I fix this?
Use fgetcsv instead of fgets.
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if (isset($data[1])) {
echo $data[1] . "<br>\n";
}
}
fclose($handle);
}
It looks like you were intending to call fgetcsv instead of fgets. Also, the name index would be 1 then, instead of 3:
<?php
$file = fopen('test.csv', 'r');
while($row = fgetcsv($file)) {
if (isset($row[1])) {
echo $row[1], "\n";
}
}
fclose($file);
The file method returns all lines in an array. The explode method splits up a line by a particular delimiter.
$lines = file($file_name);
$fields = array();
foreach ($lines as $line) {
$cells = explode(',', $line);
$fields[] = $cells[1];
}
echo "<pre>";
print_r($fields);
echo "</pre>";
You're heading does not match your question, you want the second column, not row.
Firstly, your getting the 4th character of each row you need to do something like this (not tested):
$data=fopen('test.csv','r');
while($row=fgets($data)){
$cols = explode(',' $row);
echo $cols[1]."<br>\n";
}

PHP fgetcsv - Skip columns?

I am trying to import a CSV, and be able to remove columns, and only import the ones selected.
So I have an array of selected fields, and the CSV file. I can remove rows, but having problems skipping columns.
Here is what i'm using to display a table, just trying to test out removing the column. Nothing fancy here. Just need to know where to place any if statements, or anything. Tips, suggestions, samples all welcome!
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo("<tr>\r\n");
foreach ($data as $index=>$val) {
echo("\t<td>$val</td>\r\n");
}
echo("</tr>\r\n");
} //end while
Where do i place any if statement to allow only the remainder of rows? i've tried in_array, array_diff, etc - and nothing seems to be working?
Now that i'm typing this out, should I just use PHP to delete the columns before insert? What would be best practice?
thanks
jt
You can set an array containing the columns to display (in my ex 1 and 3) and use the key part of the foreach to know which is the column you are scanning:
<?
$handle = fopen("test.csv", "r");
$columns = array(1,3);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo("<tr>\r\n");
foreach ($data as $index=>$val) {
if (in_array($index+1, $columns)) {
echo("\t<td>$val</td>\r\n");
}
}
echo("</tr>\r\n");
} //end while
?>
Try:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo("<tr>\r\n");
foreach ($data as $index=>$val) {
if($index != BADINDEX) {
echo("\t<td>$val</td>\r\n");
}
}
echo("</tr>\r\n");
}
Where BADINDEX is the column number you want to get rid of (first column being 0).
Since what you get from fgetcsv are the rows and not the columns, one simply needs to filter out the desired column for every row printed, which is accomplished by checking the index in the foreach block.
This is old post but i found another way that may help someone:
$file = fopen($yourcsvfile, 'r');
while (($result = fgetcsv($file, 1000, ",")) !== false)
{
$temp = array();
$temp[] = $result[1]; // the column you want in your new array
$temp[] = $result[2]; // the column you want in your new array
$csv1[] = $temp;
}

Categories