使用PHP,如何从以特定值开头的文本文件中回显一行?

使用PHP,如何从以特定值开头的文本文件中回显一行?

问题描述:

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 with "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...

让我们说文本文件“data1.txt”包含: p>

  56715 ||吉姆||绿色|| 19 
5678 || Sara ||红色|| 92 
53676 || Mark || Orange || 6 
56787 || Mike || Purple || 123 
56479 || Sammy  ||黄色|| 645 
56580 ||玛莎||蓝色|| 952 
ect ... 
。
。  
  code>  pre> 
 
 

我想只回显以“5678 ||”开头的行。 “5678”是确切的$ refVal或参考值。 该行应显示如下: p>

 我的名字是:$ nameVar 
我的颜色是:$ colorVar 
我的号码是:$ numVar 
  code>  pre  > 
 
 

谢谢...... p> div>

$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    
    }
}