How to turn this text into an array with name and description?

Posted on

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:

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:



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) {
  array(2) {
    string(12) "Art Deco.jpg"
    string(20) "Descrição teste!"
  array(2) {
    string(9) "Touro.jpg"
    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>';



Leave a Reply

Your email address will not be published. Required fields are marked *