0

I have a file test.txt over 4 lines:

This
Is
A
Test

I have a PHP script which when I run grabs the contents of this file and displays for me:

<?php $file = file_get_contents('https://www.mywebsite.com/test.txt'); echo $file; ?>

Is there any way to get a specific line from the test.txt file?

michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190
  • 2
    The `file` function already gives you an array of lines, so just get the specific line from that? – Niet the Dark Absol Jul 26 '17 at 10:08
  • 2
    Use `file()` you get the contents of the file as an array where each item is a line. – Halcyon Jul 26 '17 at 10:08
  • Possible duplicate of [PHP to search within txt file and echo the whole line](https://stackoverflow.com/questions/3686177/php-to-search-within-txt-file-and-echo-the-whole-line) – Amir Jul 26 '17 at 10:10

3 Answers3

3

you could explode() with new line, like:

$string = file_get_contents('https://www.mywebsite.com/test.txt');
$stringArr = explode("\n", $string);
echo $stringArr[2]; //get the third line

or use file() which Reads entire file into an array, like:

$lines = file('https://www.mywebsite.com/test.txt');
echo $lines[2];
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
2

use this one to read file in this line

        $output = fgets($file,1); // start read file in line 1
1

Use file() instead:

<?php

$lines = file("file.txt");

foreach($lines as $line){

echo $line;
}
ArtOsi
  • 913
  • 6
  • 13