0

I have a text file named Profile.txt which is in key:value pair form.

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?

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);
  ?>
1
  • What have you tried so far? Commented Jun 16, 2019 at 13:26

2 Answers 2

1

Cany ou try this

$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();
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah that worked too..Thank you for giving it time.I appreciate that
1

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

4 Comments

Hey thanx pal..but what if Name: ABC would be Name :ABC..that's not working.
@yash you need to trim() that.
Thnx @vivek_23 pal
Did update my solution with trim() on the keypair[0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.