php - how to get the content from a txt file into an array
Get the solution ↓↓↓For some reason, i want to separate the keys and values from an associative array and read them from a txt file:
Below is what i did have
// translations
$lang = array(
'All Articles' => 'Alle Artikelen',
'Page' => 'Pagina',
'from' => 'van'
);
Now i want to change it like this:
$lang = array(
file_get_contents("translations.txt"); // read the associative array
);
andtranslations.txt
only contains:
'All Articles' => 'Alle Artikelen',
'Page' => 'Pagina',
'from' => 'van',
This does not work. How can i read out the key/value pairs when they are stored in an txt file like above?
Answer
Solution:
This is not possible to get file content and directly assign to an array. You need to parse file, extract lines then extract key and value.
$str = file_get_contents("translations.txt");
$lang = [];
foreach (explode("\n", $str) as $line)
{
if (strpos($line, '=>') === false)
{
continue;
}
list($key, $value) = explode('=>', $line);
$lang[trim($key,'\' ')] = trim(trim($value), '\',');
}
By usingexplode
extract lines based on line break(\n
).
if (strpos($line, '=>') === false)
is a control for avoid error on empty lines (usually end of file)
Even beter use json file:
translations.json
{"All Articles":"Alle Artikelen","Page":"Pagina","from":"van"}
And php code:
$lang = json_decode(file_get_contents(public_path('lang.json')), true);
var_dump($lang);
Answer
Solution:
This could be dangerous. It will execute the code in the file.
eval(
'$lang = array('.
file_get_contents("translations.txt"). // read the associative array
');'
);
echo '<pre>';
var_dump($lang);
Output:
array(3) {
["All Articles"]=>
string(14) "Alle Artikelen"
["Page"]=>
string(6) "Pagina"
["from"]=>
string(3) "van"
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.