Albert Paul
Albert Paul

Reputation: 1218

PHP:Can't retrieve line by line text from a text file with php

I have a text file in my server which changes dynamically and i wanted to print specific line of the text file in my php page also i wanted to trim the current line. For example,Assume data.txt

score=36
name=Football Cup
Player=albert

and i wanted to print like this in my page
36
Football Cup
albert

So how can i print specific words or sentence from a text file which is dynamically changes.

Upvotes: 0

Views: 91

Answers (3)

Kevin Nielsen
Kevin Nielsen

Reputation: 4433

If the data will always be in that or a similar format, you can use PHP's built-in config file parser to load the data and then refer to its values via array index.

$data = parse_ini_file( "data.txt" );
echo $data["name"]."\n";

No string manipulation or for loop required.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324810

In this case it looks like all you need is:

foreach(file("data.txt") as $line) {
    list($k,$v) = explode("=",$line,2);
    echo $v."<br />";
}

If you're running PHP 5.4, you can use the shorter:

foreach(file("data.txt") as $line) echo explode("=",$line,2)[1]."<br />";

Upvotes: 3

dan-lee
dan-lee

Reputation: 14502

If it is always name=WORD then you can go with this:

$file = file('data.txt')

// iterate through every line:
foreach($file as $line) {
  // split at the '=' char
  $parts = explode('=', $line, 2); // limit to max 2 splits

  // and the get the second part of it
  echo $parts[1];
}

Upvotes: 1

Related Questions