Reputation: 91
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);
?>
Upvotes: 0
Views: 553
Reputation: 519
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;
}
}
Upvotes: 1
Reputation: 6341
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();
Upvotes: 1