-2

I am importing a .txt file using the while(!feof function. It works fine.

But now I need to only import the 2nd and 4th position/value of each line.

How can that be done?

Below you can see the code I am currently using. That code imports the whole file - line by line.

$txtimport = fopen("MyFile.txt", "r") or die("I died");
// Output one line until end-of-file
echo '<div id="someID" style="display: block">';
while(!feof($txtimport)) {
echo '<ar>'.fgets($txtimport).'</ar><br />';
}
echo '</div>';
fclose($txtimport);

The .txt file looks like this:

1;Hello;World;How;Are;You?
A;I;am;fine;thank;you
Good;to;hear;from;you;again

Expected output

Hello How
I fine
to from

Notice
The .txt. file follows the same logic for each line. Each line consists of 6 positions splitted by ";"

Logic
sometekst1;sometekst2;sometekst3;sometekst4;sometekst5;sometekst6

Ironhand
  • 19
  • 4

2 Answers2

1

You can use explode():

$txtimport = fopen("MyFile.txt", "r") or die("I died");

echo '<div id="someID" style="display: block">';
while (($line = fgets($txtimport)) !== false) {
    $parts = explode(";", $line);
    echo "<span>$parts[1]</span><span>$parts[3]</span><br/>";
}
echo '</div>';
fclose($txtimport);
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Using the standard fgetcsv() but with a delimiter of ; (the third parameter) will allow you to read the file directly as a series of fields and then output the individual items...

$txtimport = fopen("MyFile.txt", "r") or die("I died");
// Output one line until end-of-file
echo '<div id="someID" style="display: block">';
while($data = fgetcsv($txtimport, null, ";" )) {
    echo '<ar>'.$data[1]." ".$data[3].'</ar><br />';
}
echo '</div>';
fclose($txtimport);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55