CSV file to array with entry validation in PHP - php

I tried to convert an csv file to an array with str_getcsv in php. Afterwards I want to check if the form submit is in the csv file alreaddy.
My code:
//get form input
$email = $_POST["email"];
//create array
$csv = array('str_getcsv', file('file.csv'));
//functio to check csv content for $email
function val() {
if (in_array($email, $csv)) {
echo "Enthalten";
}
else {
echo "Nicht enthalten";
}
}
The check is working now. But the code inside of the else {} statement ist not.
<?php
$email = $_POST["email"];
$csv = array_map('str_getcsv', file('file.csv'));
foreach ($csv as $row) {
if (in_array($email, $row)) {
echo "Error";
} else {
// this code is working fine if seperated
$list = array (array($email),);
$fp = fopen('file.csv', 'a');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
// here is a working skript to send an email to the $email recipient
}
}
?>

array_map('str_getcsv', file('file.csv')) will return a multi-dimensional array. in_array() isn't going to work like this.
You'll need to iterate over each row in the CSV to look for the email.
//get form input
$email = $_POST["email"];
//create array
$csv = array_map('str_getcsv', file('file.csv'));
foreach ($csv as $row) {
if (in_array($email, $row)) {
echo "Enthalten";
} else {
echo "Nicht enthalten";
}
}

first convert your csv file into array.
$csv = array_map('str_getcsv', file('file.csv'));
secondly, use array_search for the email inside the array above. (e.g: http://php.net/manual/en/function.array-search.php)
$key = array_search($email, $csv);
if email exist, it will return you the key inside the array.

Related

Create key-value pair from csv php

I have a csv file like below
tl_blade_thickness,tl_blade
test1,test1
test2,test2
test3,test3
test4,test4
test5,test5
test6,test6
test7,test7
test8,test8
test9,test9
I'm trying to create a key value pair array like below.
["tl_blade_thickness"=>["test1","test2","test3",...],tl_blade=>["test1","test2","test3",...]]
I tried like this below.
$content = fopen("csv.csv", "r");
$all_rows = array();
$header = fgetcsv($content);
while ($row = fgetcsv($content)) {
$all_rows[] = array_combine($header, $row);
}
Use the first line of the file to create the keys of the array. Then push each field of the remaining lines into the corresponding element keys.
$content = fopen("csv.csv", "r");
$headers = fgetcsv($content);
$all_rows = array_fill_keys($headers, []);
while ($row = fgetcsv($content)) {
foreach ($headers as $i => $name) {
$all_rows[$name][] = $row[$i];
}
}

PHP Read csv data without first line

I want to store csv columns data into array
I have did this so far.
$csvfile = file('testfile.csv');
$csvData = [];
foreach ($csvfile as $key => $line) {
$csvData[] = str_getcsv($line);
}
This works fine but the first line also include in array
I want to skip first line
Remove the first element of the array with array_shift().
$csvfile = file('testfile.csv');
array_shift($csvfile);
$csvData = array_map('str_getcsv', $csvfile);
or you can do like this
$csvfile = file('testfile.csv');
unset($csvfile[0]);
$csvData = [];
foreach ($csvfile as $key => $line) {
$csvData[] = str_getcsv($line);
}

How to convert JSON data to CSV format on the fly with out using csv file

I am using PHP and converting the JSON data into the CSV format and later on read the same CSV file for further processing.
Below is my code that converts the JSON data in to the CSV format.
function LoadDataFromFile($file)
{
$json = file_get_contents($file);
$array = json_decode($json, true);
$f = fopen('out.csv', 'w');
$firstLineKeys = false;
$keys = array();
//first collect keys
foreach($array as $line){
foreach($line as $key => $value){
if(!in_array($key, $keys))
$keys[] = $key;
}
}
$keyString = implode(",", $keys);
fwrite($f, "$keyString\n");
foreach ($array as $line)
{
$outputArray = array();
foreach($keys as $key){
if(array_key_exists($key, $line)){
$outputArray[] = str_replace(',', '', $line[$key]);;
} else {
$outputArray[] = "";
}
}
$outputString = implode(",", $outputArray);
fwrite($f, "$outputString\n");
}
fclose($f);
}
As we can see that, i am writing data into the "out.csv" file, and later on i am reading same CSV file and assign the value/ full contents of the same file line by line to $array variable, as shown below.
$array = explode("\n", file_get_contents('out.csv'));
Now, I want to directly assign the value of csv contents into the $array variable with out using the intermediate "out.csv" file.
Wondering what data structure should i use while converting JSON data to CSV format, and possible code changes required for "LoadDataFromFile" method?
If you can already convert the json into csv, then just append the output strings together assigned to a string variable instead of writing it to a file. Or am I misunderstanding what you want?
Instead of:
fwrite($f, "$outputString\n");
you can put:
$csv .= $outputString;
And finish it with:
$array = explode("\n", $csv);

deleting matches from text file in php

Consider a txt file of a list of items
qqqqqq
eeeeee
dddddd
hhhhhh
dddddd
hhhhhh
999999
And some of the items in the list are duplicates. how do I output a using php a text file where anything that is duplicated is removed.
the result:
qqqqqq
eeeeee
999999
You can use array_unique
and then right the content back
$file = fopen("filename.txt", "r");
$members = array();
while (!feof($file)) {
$members[] = fgets($file);
}
fclose($file);
$unique_members = array();
$unique_members = array_unique($members);
var_dump($unique_members);
//write the content back to the file
The above solution was for removing the duplicates only and make them unique. Thanks to nhahtdh for pointing it out.
$count_members = array_count_values($members);
foreach($count_members as $key=>$value)
{
if($value == 1)
//write it to the file
}
So you will not need the array_unique stuff
Sorry again
<?php
$file = file_get_contents('file.txt'); //get file to string
$row_array = explode("\n",$file); //cut string to rows by new line
$row_array = array_count_values(array_filter($row_array));
foreach ($row_array as $key=>$counts) {
if ($counts==1)
$no_duplicates[] = $key;
}
//do what You want
echo '<pre>';
print_r($no_duplicates);
file_put_contents('no_duplicates.txt',$no_duplicates); //write to file. If file don't exist. Create it.

PHP read in specific csv file column as an array

I am new to PHP and would like to be able to read in a csv file which has two columns, one is the number (kind of like a ID) then the other holds a integer value. I have looked up the fgetcsv function but I have not been able to find a way to read a specific column from the csv file.
I would like to get all the values from the second column only, without the heading.
Any way of doing this?
This is what I have so far:
$file = fopen('data.csv', 'r');
$line = fgetcsv($file);
And this is some sample data from the csv file:
ID,Value
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00
Any help would be appreciated.
Thanks.
fgetcsv() only reads a single line of the file at a time. You'll have to read the file in a loop to get it all:
$data = array();
while($row = fgetcsv($file)) {
$data[] = $row;
}
The heading you can skip by doing an fgetcsv once outside the loop, to read/trash the header values. And if you only want the second column, you can do:
$data[] = $row[1];
However, since you've got data in there, maybe it might be useful to keep it, plus key your new array with the ID values in the csv, so you could also have:
$data[$row[0]] = $row[1];
and then your nice shiny new array will pretty much exactly match what's in the csv, but as an array keyed by the ID field.
$csv = array_map("str_getcsv", file("data.csv", "r"));
$header = array_shift($csv);
// Seperate the header from data
$col = array_search("Value", $header);
foreach ($csv as $row) {
$array[] = $row[$col];
}
// Iterate through data set, creating array from Value column
$header = fgetcsv($h);
$rows = array();
while ($row = fgetcsv($h)) {
$rows []= array_combine($header, $row);
}
$fp = fopen($filePath, "r+");
$header = fgetcsv($fp);
while ($members = fgetcsv($fp)) {
$i = 0;
foreach ($members as $mem) {
$membersArray[ $i ][ ] = $mem;
$i++;
}
}
$newArray = array_combine($header, array_map("array_filter",$membersArray));
You can also use this class http://code.google.com/p/php-csv-parser/
<?php
require_once 'File/CSV/DataSource.php';
$csv = new File_CSV_DataSource;
$csv->load('data.csv');
var_export($csv->connect());
?>

Categories