Receive external JSON data by PHP

12

I'm trying to get an external JSON file via PHP. I'm doing it this way:

<?php

$json_file = file_get_contents(
     "http://www.moonwalk.com.br/api/VitrineDeProdutos/58e903df295cbc5c4639434d4c35090d");

$json_str = json_decode($json_file, true);

$itens = $json_str->nodes;

foreach ( $itens as $e ) 
    { echo "$e->title<br>"; } 
?>

But I'm not getting any results.

The external JSON files are at this address .

Am I doing something wrong?

    
asked by anonymous 05.02.2014 / 18:52

3 answers

6

The second parameter of the json_decode () is to force the decode result to the structure of a associative array.

Your code is correct if you do not have true in json_decode .

If you have true then you should expect an associative array, in which case you can use:

$json_file = file_get_contents("http://www.moonwalk.com.br/api/VitrineDeProdutos/58e903df295cbc5c4639434d4c35090d");   
$json_str = json_decode($json_file, true);
$itens = $json_str['nodes'];

foreach ( $itens as $e ) 
    { echo $e['title']."<br>"; } 

Example

    
05.02.2014 / 19:00
6

Get the result by removing true from json_decode() .

json_decode($json_file);
  

json_decode (string $ json [ bool $ assoc = false [ int $ depth = 512 [ int $ options = 0]]] php.net

The second parameter forces the return of json_decode () to be an associative array , while on the lines below you were trying to access an object.

$itens = $json_str->nodes;

If you have any errors in the conversion, use the functions json_last_error () (since php5.3) and json_last_error_msg () (from php5.5) to detect the cause.

    
05.02.2014 / 18:56
0

Do you want to receive a json object like that?

{
    "nome" : "ra"
}

Example and submission (POST)

<?php

$request = new HttpRequest();
$request->setUrl('http://localhost:8080/usuariosapi.php');
$request->setMethod(HTTP_METH_POST);

$request->setQueryData(array(
  'acao' => 'consultarpornome'
));

$request->setHeaders(array(
  'postman-token' => 'd26d9873-4dda-705f-55a3-512f4acd3e18',
  'cache-control' => 'no-cache'
));

$request->setBody('{
    "nome" : "ra"
}');

try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}

In the target PHP file you use this command to retrieve the JSON object

header('Content-Type: application/json; charset=utf-8');  

$json = file_get_contents('php://input');
$obj = json_decode($json);

I hope it helps you

    
13.09.2016 / 21:47