Return txt lines to JSON in PHP

Asked

Viewed 111 times

0

Friends, help me with my class? I’m taking a programming course and I’m getting beat up with JSON.

I have a text file (.txt) with 5 lines containing the names of the students in my classroom so I need to retouch them with JSON and then work them individually in PHP.

Archive students.txt

João Gilberto
Pedro Simões
Fernando Leal
Jaqueline Silveira
Luana Godói

The professor said I need to do this with the json_encode and then use the command for to return, but honestly I haven’t been able to work them individually.

$linhas = explode("\n", $$txt); //Separo cada linha do arquivo txt

$nomes = array();   
for($i = 0; $i <= count($linhas)-1; $i++) { //Percorro cada uma das linhas

    $nome = $linhas[$i];

}

echo json_encode($nome);

I know I’m doing something very wrong, because it’s retonando null...

1 answer

1


You can do it this way:

<?php
   $arquivo = file("alunos.txt");
   $json = json_encode($arquivo);

The function file("alunos.txt") will be to take each row of the file and separate them within one array and then move on to the JSON with json_encode().

You can also try this way here:

<?php
    $arquivo = file_get_contents("alunos.txt")
    $arquivo = explode("\n", $arquivo);

    $json = json_encode($arquivo);

but recommend the above way for being smaller and having the same functionality, always look for the simplest way to solve any problem.

  • That’s perfect! Very easy! Just for clarification: and if I took the content via file_get_contents and used the for as I suggested upstairs? The way you did already helps me with the task, yes. But thinking left me the doubt. But I already thank Angelo enormously!

  • for is not needed in your code, just explode and json_encode already serve

Browser other questions tagged

You are not signed in. Login or sign up in order to post.