Read specific line from csv file on php [duplicate] - php

This question already has answers here:
PHP dynamically create CSV: Skip the first line of a CSV file
(8 answers)
Closed 3 years ago.
How do I get the second line from this CSV file?
<?php
$file = file('list.csv');
while (($line = fgetcsv($file)) !== FALSE) {
print_r($line);
}
?>

You can use an iterator to apply condition
$file = file('list.csv');
$i = 0;
while (($line = fgetcsv($file)) !== FALSE) {
if($i == 1){
print_r($line);
break;
}
$i++
}

Firstly file() reads the file into an array, so you don't need that - just open it using fopen() (and don't forget to close it), then if you only want the second line, then just call fgetcsv() twice...
$file = fopen('list.csv', r);
$line = '';
if (fgetcsv($file) !== FALSE) {
$line=fgetcsv($file);
}
fclose($file);

Related

PHP - Notice Undefined offset

I have an issue in my php script which I don't understand. I know there are several questions regarding this issue but none fits to my issue.
I actually have one input file delimited by tabulation named testfile.txt.
With this txt file, I create a new file named result.txt where I take content of testfile in column 0 and column 7.
When I execute my php script, I get this error:
Notice: Undefined offset: 7
The thing that I don't understand is, my result.txt is well created with data contained in my column 0 and 7 from my testfile.txt. If I do:
echo $dataFromTestFile[7];
I have in output contents in column 7.
So I don't really understand why I have this notice and how to remove it.
Here's my php script:
<?php
if (false !== ($ih = fopen('/opt/lampp/htdocs/ngs/tmp/testfile.txt', 'r'))) {
$oh = fopen('/opt/lampp/htdocs/ngs/tmp/result.txt', 'w');
while (false !== ($dataFromTestFile = fgetcsv($ih,0,"\t"))) {
// this is where I build my new row
$outputData = array($dataFromTestFile[0], $dataFromTestFile[7]);
fputcsv($oh, $outputData);
//echo $dataFromTestFile[7];
}
fclose($ih);
fclose($oh);
}
?>
Sample data of testfile.txt:
Input Errors AccNo Genesymbol Variant Reference Coding Descr. Coding
aaa ddd fdfd dfdf fefefd ref1 fdfdfd fdfdf dfdfde
I suspect this is the line that's causing the error:
$outputData = array($dataFromTestFile[0], $dataFromTestFile[7]);
You are trying to use array elements at specific index without checking if they actually exists.
Also, you are trying to write an array object to the result file, did you mean to create a comma separated value in that file?
Try this:
$source = '/opt/lampp/htdocs/ngs/tmp/testfile.txt';
$result = '/opt/lampp/htdocs/ngs/tmp/result.txt';
if (($handle = fopen($source, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
if (isset($data[0]) && isset($data[7])) {
file_put_contents($result, $data[0] .','. $data[7] ."\r\n");
}
}
fclose($handle);
}
Alternatively, you could write the result as a csv like this also:
$sourceFile = '/opt/lampp/htdocs/ngs/tmp/testfile.txt';
$resultFile = '/opt/lampp/htdocs/ngs/tmp/result.txt';
$resultData = array();
// Parse source file
if (($handle = fopen($sourceFile, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
if (isset($data[0]) && isset($data[7])) {
$resultData[] = array($data[0], $data[7]);
}
}
fclose($handle);
}
// Write result file
if (sizeof($resultData)) {
$h = #fopen($resultFile, 'w');
if (!$h) {
exit('Failed to open result file for writing.');
}
foreach ($resultData as $resultRow) {
fputcsv($h, $resultRow, ',', '"');
}
fclose($h);
}
make sure the column 7 exists in your testfile.txt - i guess when starting from zero it may be column number 6 - also you can
var_dump($dataFromTestFile)
in order to get the content of the variable - array keys and values might be of interest for your issue

Read a line in file txt in PHP [duplicate]

This question already has answers here:
PHP: Read Specific Line From File
(13 answers)
Closed 7 years ago.
I want read a line in file text. EX line 5. Any body can help me????
$fp=fopen("test.txt",r)or exit("khong tim thay file can mo");
while(!feof($fp)){
echo fgets($fp);
}
fclose($fp);
Thanks for read
You can use the fgets() function to read the file line by line:
<?php
$handle = fopen("test.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line.'<br/>';
}
fclose($handle);
} else {
// error opening the file.
}
?>
$myFile = "text.txt";
$lines = file($myFile);//file in to an array
echo $lines[1]; //line 2
PHP - Reads entire file into an array
Just put an incremental counter in your loop, only echo if that counter matches your requred line number, then you can simply break out of the loop
$required = 5;
$line = 1;
$fp=fopen("test.txt",r)or exit("khong tim thay file can mo");
while(!feof($fp)){
if ($line == $required) {
echo fgets($fp);
break;
}
++$line;
}
fclose($fp);

get the first 3 lines of a text file in php [duplicate]

This question already has answers here:
How to read a large file line by line?
(14 answers)
Closed 8 years ago.
I am developing a website in PHP, and I must include in the index the first 3 lines of a text file in PHP. How can I do that?
<?php
$file = file_get_contents("text.txt");
//echo the first 3 lines, but it's wrong
echo $file;
?>
Even more simple:
<?php
$file_data = array_slice(file('file.txt'), 0, 3);
print_r($file_data);
Open the file, read lines, close the file:
// Open the file for reading
$file = 'file.txt';
$fh = fopen($file, 'rb');
// Handle failure
if ($fh === false) {
die('Could not open file: '.$file);
}
// Loop 3 times
for ($i = 0; $i < 3; $i++) {
// Read a line
$line = fgets($fh);
// If a line was read then output it, otherwise
// show an error
if ($line !== false) {
echo $line;
} else {
die('An error occurred while reading from file: '.$file);
}
}
// Close the file handle; when you are done using a
// resource you should always close it immediately
if (fclose($fh) === false) {
die('Could not close file: '.$file);
}
The file() function returns the lines of a file as an array. Unless the file is huge (multiple megabytes), you can then use array_slice to get the first 3 elements of this:
$lines = file('file.txt');
$first3 = array_slice($lines, 0, 3);
echo implode('', $first3);

Modify a csv file line by line

I have a big file that I want to modify every line in it.
I want to use PHP to do it quickly :
My file is CSV file ;
20010103,02,00,00,0.9496
20010103,03,00,00,0.9504
20010103,04,00,00,0.9499
I want to make it like this to be able to use it late with Highchart:
[Date.UTC(2001,01,03,02,00,00),0.9496],
[Date.UTC(2001,01,03,03,00,00),0.9504],
[Date.UTC(2001,01,03,04,00,00),0.9499],
How canI loop every line and make this modification ?
See the fgetcsv and fputcsv PHP functions. It will basically be something like:
if (($handle1 = fopen("input.csv", "r")) !== FALSE) {
if (($handle2 = fopen("output.csv", "w")) !== FALSE) {
while (($data = fgetcsv($handle1, 1000, ",")) !== FALSE) {
// Alter your data
$data[0] = '...';
// Write back to CSV format
fputcsv($handle2, $data);
}
fclose($handle2);
}
fclose($handle1);
}
Try this code:
<?php
$filename = 'info.csv';
$contents = file($filename);
foreach($contents as $line) {
$data = explode(",",$line);
$val = "[Date.UTC(".substr($data[0],0,4).",".(substr($data[0],4,2)).",".substr($data[0],6,2).",".$data[1].",".$data[2].",".$data[3]."),".$data[4]."],";
}
?>

CSV file read fail (PHP )

I am trying to read a CSV file (delimited by commas) but unfortunately, it isn't responding as it ought to. I am not so sure what I am doing wrong here, but I'll paste out the contents of the code and the CSV file both :
$row = 0;
if($handle = fopen("SampleQuizData.csv","r") !== FALSE)
{
// WORKS UNTIL HERE, SO FILE IS BEING READ
while(!feof(handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo $line[2]; // DOES NOT WORK
}
}
Here is the CSV file: (the emails and names have been changed here to protect the identities of the users)
parijat,something,parijatYkalia#hotmail.com
matthew,durp, mdurpdurp#gmail.com
steve,vai,stevevai#gmail.com
rajni,kanth,rajnikanth#superman.com
it lacks a '$' to the handle variable
while(!feof($handle)){
and not :
while(!feof(handle)){
Give this a try:
<?php
$row = 0;
if (($handle = fopen("SampleQuizData.csv", "r")) !== FALSE)
{
while(!feof($handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo "$line[2]";
}
}
?>
It's worth a mention but when I was working on CSV exports a few weeks ago, I had weird line ending inconsistencies. So I put this at the top of my php file and it worked splendid.
<?php
ini_set("auto_detect_line_endings", true);
?>

Categories