简体   繁体   中英

PHP: echoing a few selected lines of a txt file

I need to echo only selected lines from a .txt file using PHP. The txt file content looks like this:

1 111 111 111 111 111 111 111 111 111 111
2 196 182 227 190 195 196 278 197 323 265
3 84.1 84.1 84.1 84.2 85.4 84.1 84.2 84.1 84.1 84.1
4 107 107 107 107 107 107 107 107 107 107
5 10.0 9.29 9.86 9.90 9.57 9.56 9.52 9.55 10.0 9.62
6 0.652 0.622 0.676 0.617 0.637 0.617 0.563 0.601 0.586 0.601
7 132 132 132 132 132 132 481 132 132 132
8 113 113 113 113 113 113 113 113 113 113
9 510 571 604 670 647 667 656 257 264 431
10 245 246 247 246 246 245 247 246 247 247

The previous working code was echoing every lines.

$fp = fopen("http://xxx/myfile.txt","r");
while (!feof($fp)) {
$page .= fgets($fp, 4096); 
}
fclose($fp); 
echo $page;
break;

I'm trying to get the same formating but only with the selected lines. For instance let say only lines: 3, 5, 8, 10.

The second step would then be if the lines could be echoed in a different order than the initial one.

If someone knows a simple way to do it, that would be excellent!
Thanx in advance.

$lines = file('http://xxx/myfile.txt');

print $lines[2];  // line 3
print $lines[4];  // line 5
...

see file()

here's an example of how it can be done:

function echo_selected_lines_of_file($file, array $lines)
{
    $fContents = file_get_contents($file); // read the file
    $fLines = explode("\n", $fContents); // split the lines
    foreach($fLines as $key=>$fLine) // foreach line...
        if(in_array($key, $lines)) //if its in the $lines array, print it
            echo $fLine.'<br>';
}

echo_selected_lines_of_file('index.php', array(1,4,7));

You could use the file() which converts each line into a array. But if your file is big it will consume a bit of memory.

$lines_to_print = [1,3,5,8];

$lines = file('file.txt');
for($i in $line_to_print) {
    echo $lines[$i];
}

An efficient solution is

$i = 0;
$lines_to_print = [1,3,5,8];

$file = fopen("file.txt", "r");
while(!feof($file)){
    $line = fgets($file);
    if(in_array(++$i, $lines_to_print)) {
        echo $line
    }
}
fclose($file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM