Question :
I have a .txt file. It has the name of the images and the description about them. So I wanted to do it like this:
nome:descrição
imagem1.jpg:"descrição exemplo 1";
I know how to read the php file. Now I wanted to separate the information, but I do not know what function in PHP can do this, in order to have $nome
and $descrição
in different variables.
Answer :
You can do it this way:
First open the text content and save it to a variable:
$string = file_get_contents('arquivo.txt');
Next we will create an array with each line of the file.
$array = array_filter(explode("n", $string));
Now let’s map the array
so that it turns the division of :
into a array
of 2 items. Then we will use array_combine
to combine keys with the two values (keys will be “name” and “description”)
$callback = function ($value) {
return array_combine(array('nome', 'descricao'), explode(":", $value, 2));
};
$array = array_map($callback, $array);
Finally, we can see the result:
var_dump($array);
Improvements
Instead of using file_get_contents
and then a explode
in n
, we can evolve in this expression using the file
function:
$array = array_filter(file('arquivo.txt'));
In this case, the file
function already opens the file, leaving each line in an element of array
.
To scroll through the values, simply use foreach
:
foreach ($array as $key => $value) {
echo $value['descricao'];
echo $value['nome'];
}
See an example at Ideone
You can use file()
:
$arquivo = file('arquivo.txt');
foreach($arquivo as $index => $linha){
list($info[$index]['imagem'], $info[$index]['descricao']) = explode(':', trim($linha));
}
This will result in:
array(2) {
[0]=>
array(2) {
["imagem"]=>
string(12) "Art Deco.jpg"
["descricao"]=>
string(20) "Descrição teste!"
}
[1]=>
array(2) {
["imagem"]=>
string(9) "Touro.jpg"
["descricao"]=>
string(19) "Descrição teste!2"
}
}
So you can manipulate the array as you want, it’s not clear how or what the goals are after reading the data, if you want to display them you can do:
foreach($arquivo as $linha){
list($imagem, $descricao) = explode(':', trim($linha));
echo '<img src="'.$imagem.'" />';
echo '<p>'.$descricao.'</p>';
}