Using PHP, how do I echo a line from a text file that starts with a specific value?
Lets say the text file " data1.txt" contains:
56715||Jim||Green||19
5678||Sara||Red||92
53676||Mark||Orange||6
56787||Mike||Purple||123
56479||Sammy||Yellow||645
56580||Martha||Blue||952
ect...
.
.
I would like to echo only the line beginning w开发者_开发百科ith "5678||". "5678" is the exact $refVal or reference value. The line should display like this:
My name is: $nameVar
My color is: $colorVar
My number is: $numVar
Thanks...
$fh = fopen('data1.txt', 'r') or die('Unable to open data1.txt');
while($line = fgetcsv($fh, 0, '||')) {
if ($line[0] == 5678) {
echo <<<EOL
My name is: $line[1]
My color is $line[2]
My number is $line[3]
EOL;
break; // if there's only ever one '5678' line in the, get out now.
}
}
fclose($fh);
alternate version, as suggested by Jared below. Probably will be faster, as it only does the array creation on the line that actually matches, and not for each line as the fgetcsv version does.
$fh = fopen('data1.txt', 'r') or die('Unable to open data1.txt');
while($line = fgets($fh)) {
if (strpos($line, '5678||') === 0) { // only if right at start of string
$data = explode('||', $line);
echo <<<EOL
my name is blah blah blah
EOL;
break;
}
}
You can split each line into an array using explode
, like so:
foreach ($lines as $line)
{
$t = explode('||', $line);
if ($t[0] == $refVal) {
// echo the rest of $t array however you want
// $t[1] would be the name, $t[2] the color, etc
}
}
精彩评论