从php中的textfile中获取字符串条目

时间:2015-07-10 18:33:44

标签: php file fwrite fread

我有一个问题。如何从文本文件中的条目中获取字符串。

texfile看起来像:

Blabla2|123456
Blablablabla4|475387638
Blab1|387549900

现在我想从Blablablabla4获得|

背后的数字

读取文件的功能是什么?

2 个答案:

答案 0 :(得分:1)

将每行文件加载到$line,然后使用函数explode('|', $line_variable)将字符串与int分开。

$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $line = explode('|', $line);
        $string = $line[0];
    }

    fclose($handle);
 } else {
    // error opening the file.

}

答案 1 :(得分:1)

如果您经常使用不同的密钥,则可以创建自定义函数。

function getValueFromFile($file, $key){
    if (($handle = fopen($file, "r")) !== FALSE) {
      while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
        if($data[0] == $key){
            fclose($handle);
            return $data[1];
        }
      }
      fclose($handle);
    }
    return false;
}

简单地称之为:

echo getValueFromFile("your file name", "Blablablabla4");
相关问题