Error reading dynamically generated JSON with file_get_contents

2

I have this code that generates a json file to me

header("Content-Type: application/json; charset=utf-8;"); 
$codigo = $_GET['cod']; //variável para parametro que será passado ao servidor via    
URL
$sql1 = mysql_query("Select nome, valor from produtos where id_produtos = '21' "); // 
comando SQL para buscar informações do banco de dados

$jsonObj= array(); // cria uma variável que receberá um array (JSON)
while($result=mysql_fetch_object($sql1))
{
$jsonObj[] = $result;
}

$final_res =json_encode($jsonObj); // "transforma" o array recebido em JSON
echo $final_res;
exit;    

And that is returning this code to me

[{"nome":"SAO PAULO CENTRO X COPACABANA","valor":"200,00"}]

Only this one giving me error when reading it with this reading code Warning: Invalid argument supplied for foreach () in /home/mrangelc/public_html/mpitech.com/transport/test/webler.php on line 13

$json = file_get_contents('webserv.php');
$lista = json_decode($json, true);
// Veja como fica o resultado
var_dump($lista);

// Manipulando o resultado como PHP.
foreach($lista as $objeto) {
print "nome: {$objeto['nome']} ,a valor: {$objeto['valor']}";
}

$objeto = json_decode($json);

echo 'Nome: ' . $objeto->nome;
echo 'valor: ' . $objeto->valor;

What must be wrong?

    
asked by anonymous 24.02.2015 / 03:39

2 answers

1

I've simulated your case with the following code:

$json = file_get_contents('arquivo.json');
$variable = json_decode($json);
foreach ($variable as $key) {
    echo "nome: " . $key->nome;
    echo "valor: " . $key->valor;
}

And with an .json file:

[{"nome":"SAO PAULO CENTRO X COPACABANA","valor":"200,00"}]

If your var_dump of the already decoded variable (in this example is $variable ) is the one below, you should get the result to be accessed as an object of the default class of php stdClass .

array(1) {
  [0]=>
  object(stdClass)#1 (2) {
    ["nome"]=>
    string(29) "SAO PAULO CENTRO X COPACABANA"
    ["valor"]=>
    string(6) "200,00"
    }
}

I know you use php to dynamically generate your values, reviewing your results would also be a good tip.

    
27.02.2015 / 14:13
0

As said @RodrigoRigotti in his comment, making file_get_contents of a PHP file brings its source code, not the processed file.

According to this answer in English you have two options to solve this:

  • Make the included file return a value (with return , not echo ), and then include it like this:

    $json = include 'webserv.php';
    
  • If you can not change the file to return a value, you need to use output buffering :

    ob_start();
    include 'webserv.php';
    $json = ob_get_clean();
    

    You can also create a function for this, as in the accepted answer to the question in English. Highly recommended if you're going to use this kind of thing more than once.

  • 27.02.2015 / 14:28