简体   繁体   English

如何使用php从文本文件中获取特定文本?

[英]How to get specific text from text file using php?

I have a text file named Profile.txt which is in key:value pair form. 我有一个名为Profile.txt的文本文件,该文件采用key:value对形式。

For ex: 例如:

  Name: ABC
  Father's Name: XYZ
  DOB: 11-11-2011

How do I access value ABC by key Name so I could store it in database? 如何通过键名称访问值ABC,以便可以将其存储在数据库中?

Here's the code: 这是代码:

  <?php
  $my_file = fopen('../img/uploads/ABC_1/Profile.txt' ,"r");
  $content = file_get_contents('../img/uploads/ABC_1/Profile.txt');
  echo $content;
  fclose($my_file);
  ?>

You should read the content of the file into an array, then iterate through it and "explode" the lines with ":". 您应该将文件的内容读入数组,然后对其进行遍历,并使用“:”“展开”行。

Like this way 像这样

$file = file('abc_1.txt');
foreach($file as $line) {
    /**
     * $keypair[0] => Name, Father's Name, DOB
     * $keypair[1] => ABC, XYZ, 11-11-2011
     */
    $keypair = explode(":", $line);

    /**
     * Switch for getting your favorite $keypair[0]
     */
    switch( trim($keypair[0]) )
    {
        case 'Name':
            echo trim($keypair[1]);
            break;
    }
}

Cany ou try this Cany ou试试这个

$path = 'Yourpath to file';
$fileGet = file_get_contents($path);
$removedNewLine = explode(PHP_EOL,$fileGet);

foreach ($removedNewLine as $key => $string) 
{
    $ecpEach = explode(':',$string);
    $finalArray[$ecpEach[0]] = $ecpEach[1];

}

print_r($finalArray);
exit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM