How to generate JSON dynamically to feed future application?

Asked

Viewed 447 times

1

What I want to do is this: Create a minimalist application that does a database search, returns the result in JSON, and this result is interpreted by external applications via http, with no change in the minimalist application. It works as an API, but is intended to serve as a building model for other Apis. So far, I have successfully generated JSON after creating CRUD. The problem starts when I want to consume the result of this query. I can’t make the selectTable.php file serve as consumption. I want to reprocess the information in different formats, both by Jquery getjson, and PHP objects. Follow file code.

selectTable.php

    <?php header('Content-Type:' . "text/plain");
   // Testando classe CRUD
   /*  
    * Require nos scripts necessários  
    */   
require_once "control/config.php";
require_once "control/controleCentral.php";   
require_once "control/validaEntradas.php";
require_once "model/crud.class.php"; 
include "view/viewsRetornos.php"; 
   /*  
    * Atribui uma instância da classe crud   
    * e passa uma conexão como parâmetro  
    */   
   $crud = crud::getInstance(Conexao::getInstance());
    /*  
    * Variáveis contendo os valores para serem inseridos no banco de dados  
    */    
//$crud->delete(17);



 $dados = $crud->getAlltabela($dbTabela); // para todos da tabela
  if ($controleSelectTotal = true) {
     if ($controleSelectTotal != false) {
      echo '{"'."dados".'"'.":[";
    foreach ($dados as $reg): 
       $id = $reg->id ;
       $varchar1 = $reg->varchar1;
       $$varchar2 = $reg->varchar2;
      retornaSelectTotal($id, $varchar1, $$varchar2);// Função que retorna visualmente na tela os dados
      endforeach; 
      echo ' 
{
        "Id": "0",
        "Categoria": "00000",
        "Titulo": "000000"
      }


      ]}';
  } 
  }


  ?>

jsonPHP.php

<?php 
$arquivo = "selectTabela.php";

$info = file_get_contents($arquivo);
// Eu sei... eu sei....ele vai cuspir o conteúdo do PHP ao invés do JSON.
/* Relaxa que eu estou ciente. Mas não sei como escapar só o resultado deste arquivo.
Repare que eu tentei declarar 'header('Content-Type:' . "text/plain");' no início do PHP*/

$lendo = json_decode($info);

foreach($lendo->dados as $campo){

echo "<b>id:</b> ".$campo->id;
echo "<br /><b>categoria:</b> ".$campo->Categoria;
echo "<br /><b>titulo:</b> ".$campo->titulo;

}



?>

via Javascript

// Classe para chamar o Json.
function json(){
    var qtd;
    var retorno;

    // Resgatar valores.
    json.prototype.resgatarValores = function(){
        $('#resultado').html('Carregando dados...');

        // Estrutura de resultado.
        $.getJSON('../jsonPHP.php', function(data){
            this.qtd = data.dados.length;
            this.retorno = '';

            for (i = 0; i < this.qtd; i++){
                this.retorno += 'ID: ' + data.dados[i].id + '<br />';
                this.retorno += 'Categoria: ' + data.dados[i].Categoria + ' - ';
                this.retorno += 'titulo: ' + data.dados[i].titulo + '<br /><br />';
            }

            $('#resultado').html(this.retorno);
        });

    }

}

// Objeto.
var obj = new json();
obj.resgatarValores();

For curiosity, when saving a JSON file (which is not what I want) and pointing to these scripts, everything works normally. But remember, it’s not what I want. I want to dynamically generate json. If anyone wants to test, follow below:

{"dados":[{"id":"1","Categoria":"João Carlos","titulo":"joca"},{"id":"5","Categoria":"Pedro Henrique","titulo":"[email protected]"},{"id":"7","Categoria":"Carlos Manuel","titulo":"[email protected]"},{"id":"8","Categoria":"Carlos Manuel2","titulo":"[email protected]"},{"id":"9","Categoria":"Novo Manuel","titulo":"[email protected]"},{"id":"10","Categoria":"hackeado","titulo":"[email protected]"}, 
{
        "Id": "0",
        "Categoria": "00000",
        "Titulo": "000000"
      }


      ]}

1 answer

0


Just put the full path of the URL you want to get the JSON read in the jsonPHP.php file. Rather than include with code and everything, this will cause only the HTTP output of the file to be performed.

Right:

$arquivo = "http://localhost/novoMVC/areaDeTrabalho/selectTabela.php";

Wrong:

$arquivo = "selectTabela.php";

Browser other questions tagged

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