简体   繁体   中英

How to pick only every 2nd and 4th value of a line using while(!feof)?

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);

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

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

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);

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);

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