php从文本文件中检索数据

Mdl*_*dlc 3 php

想象一下,我有一个像这样的文本文件:

 Welcome to the text file!
 -------------------------
 Description1: value1
 Description2: value2
 Description containing spaces: value containing spaces
 Description3: value3
Run Code Online (Sandbox Code Playgroud)

将这些数据存储到文本文件中很容易,如下所示:

 $file = 'data/preciousdata.txt';
 // The new data to add to the file
 $put = $somedescription .": ". $somevalue;
 // Write the contents to the file, 
 file_put_contents($file, $put, FILE_APPEND | LOCK_EX);
Run Code Online (Sandbox Code Playgroud)

每次写入时都会有不同的描述和价值.

现在我想读取数据,所以你会得到这个文件:

 $myFile = "data/preciousdata.txt";
 $lines = file($myFile);//file in to an array
Run Code Online (Sandbox Code Playgroud)

可以说我只是在文本文件中写了"color:blue"和"taste:spicy".我不知道它们是哪一行,我想要检索"color:"描述的值.

编辑 我应该让PHP"搜索"文件,返回包含"描述"的行号,然后将该行放在一个字符串中并删除":"的所有内容?

Iva*_*ova 7

通过爆炸,您可以创建一个数组,其中包含"描述"作为键,"值"作为值.

$myFile = "data.txt";
$lines = file($myFile);//file in to an array
var_dump($lines);

unset($lines[0]);
unset($lines[1]); // we do not need these lines.

foreach($lines as $line) 
{
    $var = explode(':', $line, 2);
    $arr[$var[0]] = $var[1];
}

print_r($arr);
Run Code Online (Sandbox Code Playgroud)

  • 使用explode的limit参数(`$ var = explode(':',$ line,2);`) (4认同)
  • 你也可以像这样修剪:$ arr [$ var [0]] = trim($ var [1]); (2认同)