open a file with php

Asked

Viewed 448 times

1

I wanted to search the file on my desktop - open that box to search for the file on the hard drive - (in my case would open a file .json), read and interpret it.

Is there any material, preferably php object oriented, for me to follow?

  • you want to do something like this: <input type="file" name="arquivo"> ?

  • Because to open the dialog box, it starts like this.

  • I didn’t know it existed. I wanted to open the file. json, build several dynamic elements with it in html and then send via ajax pro php generate something else with that file.

  • the name of this is not "open file"... it is "upload"

1 answer

1

I believe it’s something like, Filing cabinet: mydata.json

 {
  "dataConsulta": "2015-08-02 00:33:20",
  "listaUsuarios": [
    {
      "idUsuario": 1,
      "nome": "Renan",
      "idade": "23",
      "listaEspecialidades": ["PHP", "JS", "MySQL"]
    },
    {
      "idUsuario": 2,
      "nome": "Denali",
      "idade": "23",
      "listaEspecialidades": ["PHP", "JS", "MySQL", ".NET", "SQL Server"]
    }
    ],
    "mensagem": "2 registros encontrados",
    "especialidadesComuns": "PHP, JS, MySQL"
}

Filing cabinet: uploadJson.php

    //Move o arquivo para um lugar do servidor (A pasta já deve estar criada neste caso)
    move_uploaded_file($_FILES['arquivo']['tmp_name'],  $dstDir);
    //Pega o conteúdo do arquivo
    $fileContent = file_get_contents($dstDir);
    $objJson = json_decode($fileContent);

    //Agora use o json da forma como quiser
    //Ex.: Lista todos usuários e suas especialidades
    if(sizeof($objJson->listaUsuarios)){
      foreach($objJson->listaUsuarios as $usuario){
         echo "Nome: ".$usuario->nome.";";
         if(sizeof($usuario->listaEspecialidades)){
           echo "Especialidades: ";
           echo implode(", ", $usuario->listaEspecialidades);
         }
         echo "<br>";
      }
    }
    echo $objJson->mensagem." - Consulta realizada em: ".date("d/m/Y H:i:s", strtotime($objJson->dataConsulta))."<br>";

    if($objJson->especialidadesComuns){
       echo "Algumas especialidades são comuns entre os usuários: ".$objJson->especialidadesComuns;
    }
  }
?>

<form id="meu-form" enctype="multipart/form-data">
   <p>Selecione o arquivo: <input type="file" name="arquivo"></p>
   <input type="submit" value="Enviar">
</form>

The json_decode feature in PHP is very powerful, turning your text into an object. If you need to execute methods with the received data I suggest you use a recursive download to populate the instances of your classes with the objects received with json.

I hope I’ve helped!

Browser other questions tagged

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