Error reading dynamically generated JSON with file_get_contents

Asked

Viewed 334 times

2

I have this code that generates me a json file

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 you’re returning this code to me

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

It’s just that you’re giving me the error of reading it with this reading code Warning: Invalid argument supplied for foreach() in /home/mrangelc/public_html/mpitech.com.br/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?

  • 1

    Check the value of $lista and of $json some of them are wrong.

  • 2

    When you give a file_get_contents('webserv.php'), means you’re taking the content from it - exactly a PHP file. Replace this line with include('webserv.php'), put the query result into a variable and use this variable to generate JSON.

  • I tried to use include plus ai only repeated the result of webserv.php

  • value gives variable list probably not coming as an array, check why

  • I think that’s almost what @Rodrigorigotti said, but a simple include `

2 answers

1


I 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 a.json file:

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

Your case var_dump of the already decoded variable (in this example is the $variable) be the below, you should get the result accessed as an object of the default php class 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, revise your result would also be a good tip.

0

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

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

  1. Make the included file return a value (with return, nay echo), and then include it like this:

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

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

    It is also possible to create a function for this, as in the accepted answer of the question in English. Highly recommended if you are going to use this kind of thing more than once.

Browser other questions tagged

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