PHP - csv in_array function check - php

I am trying to pass if() statement with !in_array() check for the generated csv file.
End result is returning false for some reason, and I can not find what am I doing wrong. I am trying to pass false statement and continue with code execution.
Input:
Array with data I want to put into csv file.
Creating and inputing
data into file.
Getting the file
$list = [
0 => [
'materials'
],
1 => [
'products'
]
];
$testCsvFile = fopen("test.csv", "w");
foreach ($list as $fields) {
fputcsv($testCsvFile, $fields);
}
$projectRoot = substr(strrchr(getcwd(), DIRECTORY_SEPARATOR), 1);
$getFile = $projectRoot . '/test.csv';
$file = basename($getFile);
if ($list && is_array($list)) {
unset($parsed_data[0]);
}
if (!in_array($file, ['materials', 'products'])) {
return false;
}
.... next //

you're searching the strings without reading the file you should first open the file , read it then you should find string in array, I've pasted below code just for your reference which is searching the string in csv file after opening and reading.
$file = fopen("test.csv", "r");
$str = "materials";
while (($data = fgetcsv($file)) !== false)
{
if(in_array($str, $data))
{
foreach ($data as $i)
{
echo $i."<br>";
}
}
}
fclose($file);

Related

Value's not visible when importing CSV after values are added by fputcsv with php

I'm trying to make a translation module for my web project and i hit a wall. I written two functions, one for importing the CSV data and the other for changing, deleting and adding new data to the CSV file.
Everything works like a charm except the adding part. It adds the data to the CSV file but when i want to import it in the website via PHP it doesn't display the added values. (It see that their should be values but it gives empty results in return) the function i use for reading the csv file is:
// Load in CSV (File name, delimiter, Fixed array[key,value] (optional))
function load__CSV($filename='', $delimiter=';', $fixed = null){
if(!file_exists($filename) || !is_readable($filename)) {
return FALSE;
}
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 100000, $delimiter)) !== FALSE) {
if (!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}
fclose($handle);
}
if($fixed != null) {
foreach($data as $entry){
$set_csv[$entry[''.$fixed[0].'']] = $entry[''.$fixed[1].''];
}
} else {
$set_csv = $data;
}
return $set_csv;
}
The function i use to add, edit or remove CSV content is:
// Change csv
function update__csv($csv = 'csv/language.csv',$key = array(2,''),$values = array([3,''],[4,'']),$status = 'change') {
$input = fopen(BASE_URL.$csv, 'r');
$output = fopen(BASE_URL.'csv/temporary.csv', 'w');
while (false !== ($data = fgetcsv($input, 10000, ";"))) {
if ($data[$key[0]] == $key[1]) {
foreach ($values as $value) {
$data[$value[0]] = $value[1];
}
if ($status == 'change' || $status == 'new') {
fputcsv($output, $data, ";");
}
} else {
fputcsv($output, $data, ";");
}
}
if($status == 'new'){
fputcsv($output, $values, ";");
}
fclose( $input );
fclose( $output );
unlink(BASE_URL . $csv);
rename(BASE_URL . 'csv/temporary.csv', BASE_URL . $csv);
}
If i add new values to the CSV file and then open the CSV on my PC and safe it again (without changing a thing) to CSV with UTF-8 encoding then it works as expected and loads the correct data. If i open the CSV in Notepad++ i see this difference between manual added items and php added items:
I tried other encoding methods but that is kinda new for me so i think i did something wrong. Thank you in advance for helping me!
I did find the answer after some more debugging. One value of the array didn't contain a string but a true or false statement. This meant that it didn't add the data the right way into the CSV file.
I fixed it by adding strval() to every variable before putting it into an array.

How to parse a .csv file into a multidimensional array in PHP?

I'm a newbie in PHP and I'm trying to make a todo list that communicates with a .csv file,. So far I've managed to write a function that writes the user input into the csv file, but I'm stuck on writing a function that would parse (I'm not even sure if this is the correct term) every line of the .csv file into a multi dimensional array, so I could display every line of the list to my convenience in the PHTML file.
Here's what I have so far :
`<?php
//
// ─── DATA ────────────────────────────────────────────────────────────────────
//
$user_entry = array(
'title' => '',
'description' => '',
'date' => '',
'priority' => ''
);
// puts the data the users entered into an array
$user_entry['title'] = $_POST['title'];
$user_entry['description'] = $_POST['description'];
$user_entry['date'] = $_POST['date'];
$user_entry['priority'] = $_POST['priority'];
//
// ─── FUNCTIONS ──────────────────────────────────────────────────────────────────
//
function writeInList() {
//parses the $user_entry array into the .csv file
global $user_entry;
$file = fopen("todo.csv","a");
fputcsv($file, $user_entry, ",");
fclose($file);
}
function displayList() {
//That's where I'm stuck.
$file = fopen("todo.csv","r");
$fileCountable = file("todo.csv");
for ($i = 0; $i < count($fileCountable); $i++) {
$csvContent = fgetcsv($file, 1000, ",");
foreach ($csvContent as $value){
$var[$i] = $value;
}
echo '<br>';
}
fclose($file);
}
//
// ─── MAIN CODE ─────────────────────────────────────────────────────────────
//
writeInList();
include 'todolist.phtml';`
I'm sorry if it has been discussed before. I've searched a lot and found similar questions but can't get to make it work in my own code. Thanks a lot in advance if anyone takes the time to take a look at my code !
This is also my very first time posting here so I hope I'm doing it right.
You did pretty good. You can look at fgetcsv documentation for more. I would have change you function so it will get the argument as input (try avoid using global)
// insert data
function writeInList($user_entry, $path ) {
$file = fopen($path ,"a");
fputcsv($file, $user_entry, ",");
fclose($file);
}
//extract data
function getList($path, $limit = 100000) {
$file = fopen($path, "r");
if (!$file) return null; // or throw error or print to log
$allRows = []; //
while (($data = fgetcsv($file, $limit, ",")) !== FALSE) {
$allRows[] = $data; // as fgetcsv return array already exlode by ","
}
fclose($file);
return $allRows;
}
Now you have 2-Dim array return from getList. Use is as getList("todo.csv") and display as you pleased.
Hope that helps!

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 to pass data from a CSV file in PHP

I know this is going to be super simple when someone shows me but I can't seem to work it out. I'm trying to read in a csv file like the below and then pass it to a function called 'row'. The CSV has 4 columns, I want to read in a row and then split the data on a ',' and put it into the line $this->Row(array('','','','')); where I then want to move onto the next line, until I've finished all lines, does anyone have any ideas?
1,1,1,1
2,2,2,2
3,3,3,3
function LoadData($file)
{
$lines = file($file);
$data = array();
foreach($lines as $line){
$data[] = explode(',',trim($line));
$this->Row(array('','','',''));
}
}
Try this :
<?php
function getCsv($file) {
if (($handle = fopen($file, "r")) !== FALSE) {
while ( ( $data = fgetcsv( $handle, 100, ',' ) ) !== FALSE ) {
$this->Row($data);
}
fclose($handle);
}
}
getCsv('/path/to/file.csv');
?>

Categories