How to pass data from a CSV file in PHP - 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');
?>

Related

PHP - csv in_array function check

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

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!

replace rows from one csv file to another csv where id of is the samePHP?

I have one excel orginal.csv file
ID Name Price
1 Xblue 12
2 Yblue 32
3 Zblue 52
And another copy.csv file
ID Name Price
1 Xblue 89
2 Yblue 43
3 Zblue 45
I want to replace rows from orginal.csv to copy.csv where ID is the same.
Can I do this manually or maybe somehow using PHP?
I search for some options on the internet, but I only found getcsv and readcsv functions that can't help me in this case. Cause this is something like updating CSV file.
It may end up in request timeout in PHP because it requires so many loops to do it. If someone can reduce the time complexity of this program then it will work. if it even works it will take a lot of time to do it.
while(! feof($f_pointer)){ //open old csv to update loop1
$ar=fgetcsv($f_pointer); // getting first row
for($i=0;$i<count($ar);$i++){ //loop2 first row array
$f_pointer2=fopen("new.csv","r"); open new csv to get data
while(! feof($f_pointer2)){ // loop3 to find ID in new csv
$ar2=fgetcsv($f_pointer2); //getting each row in array
for($j=0;$j<count($ar2);$j++){ //loop4 to compare id of old csv to new csv and update data
if($ar[i] == $ar2[j]){
foreach ($ar2 as $fields) { //loop5
fputcsv($f_pointer, $fields);
}
}
}
}
}
}
?>
I've created a little soulution. If order is important you don't have to index the array and loop through the copied array.
<?php
if(file_exists('output.csv'))
{
unlink('output.csv');
}
function fputcsv_eol($handle, $array, $delimiter = ',', $enclosure = '"', $eol = "\n") {
$return = fputcsv($handle, $array, $delimiter, $enclosure);
if($return !== FALSE && "\n" != $eol && 0 === fseek($handle, -1, SEEK_CUR)) {
fwrite($handle, $eol);
}
return $return;
}
function scanFile($sFilename, $iIndexColumn)
{
$rFile = fopen($sFilename, 'r');
$aData = array();
while(($aLine = fgetcsv($rFile)) !== false)
{
$aData[$aLine[$iIndexColumn]] = $aLine;
}
fclose($rFile);
return $aData;
}
$iIndexColumn = 0;
$iValueColum = 2;
$aOriginalData = scanFile('original.csv', 0);
$aCopyData = scanFile('copy.csv', 0);
foreach($aOriginalData as $iID => $aOriginalDatum)
{
if(array_key_exists($iID, $aCopyData))
{
$aCopyData[$iID] = $aOriginalDatum;
}
}
$rFile = fopen('output.csv', 'w');
foreach($aCopyData as $aCopyDatum)
{
fputcsv_eol($rFile, $aCopyDatum, ',', '"',"\r\n");
}
fclose($rFile);

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

Categories