Retrieve multiple lines within same cell from CSV file - php

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

Related

PHP import CSV file and use data as variables

I would like to import a CSV document and parse its content to use it as variables. The document would always have fixed column names and column numbers. Any examples would be excellent.
I could only find a parse that shows the contents of the CSV file:
<?PHP
/**
* parse-csv.php
*/
$err_upTmpName = 'csvfiletutorial.csv';
$row = 0;
if (($handle = fopen($err_upTmpName, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
if($row == 0){
$row++;
} else {
// $data[0] = first name; $data[1] = last name; $data[2] = email; $data[3] = phone
if(!empty($data[0]) && !empty($data[1])) echo $data[0].' - '.$data[1].' - '.$data[2].' -
'.$data[3].' - '.$data[4].'<br/>';
}
}
} else {
echo 'File could not be opened.';
}
fclose($handle);
?>
Input sample csv:
date,value,value2
4.10.2019,15,10
Desired output csv:
using values from CSV file in a formula for example: 15+10
output=
date,sum_values
4.10.2019,25
output gets saved to a new CSV file

Store in a php array info taking from a line separated by |

I am reading a txt file on the following way:
$handle = fopen($captionTextFile, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo ($line);
}
fclose($handle);
}
// Output
IMAG0986.jpg|Title something 1 here|<b>Description</b><br />You can use HTML as you can see!
IMAG0988.jpg|Title something 2 here|<b>Description</b><br />You can use HTML as you can see!
etc...
Now I want to store only the values between the first | by line in a php array. Example of what I intend to have:
$json = '{"IMAG0986.jpg": "Title something 1 here",
"IMAG0988.jpg": "Title something 2 here"}';
In order to access this array later in this way:
$obj = json_decode($json);
print $obj->{'IMAG0986.jpg'}; // print: "Title something 1 here"
The problem that I'm having is how do I pass the values from the lines to the array? any help please?
Use file() to read the file lines to an array, then use explode() with | delimiter and add the 1st part as key and 2nd as value to an array, finally use json_encode().
Something like:
<?php
$captionTextFile = "test.pipe";
$arrayFinal = array();
$lines = file($captionTextFile);
foreach($lines as $line) {
$array = explode("|", $line);
$arrayFinal[$array[0]] = $array[1];
}
print_r(json_encode($arrayFinal));
//{"IMAG0986.jpg":"Title something 1 here","IMAG0988.jpg":"Title something 2 here"}
//If you don't need json, just access the array by key:
echo $arrayFinal['IMAG0986.jpg'];
//Title something 1 here
You can explode() the lines into keys and values in an object to achieve that desired JSON result.
$data = new stdClass();
$handle = fopen($captionTextFile, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$row = explode('|', $line);
$data->{$row[0]} = row[1];
}
fclose($handle);
}
json_encode($data);

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

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";
}

Categories