Reading JSON result with PHP

1

I have the following JSON result and I need to handle it with PHP.

JSON:

    {
  "name": "abc",
  "count": 6,
  "frequency": "Manual Crawl",
  "version": 3,
  "newdata": true,
  "lastrunstatus": "success",
  "thisversionstatus": "success",
  "thisversionrun": "Thu Jul 09 2015 11:46:39 GMT+0000 (UTC)",
  "results": {
    "collection2": [
      {
        "property11": {
          "href": "http://click.uol.com.br/?rf=meio-ambiente_home-headline-especiais-2colunas-1_1&u=http://noticias.uol.com.br/meio-ambiente/ultimas-noticias/redacao/2015/07/08/lei-mexicana-faz-com-que-tigres-e-leoes-sejam-vendidos-a-preco-de-banana.htm",
          "text": "Lei mexicana faz com que tigres e leões sejam vendidos a \"preço de banana\""
        }
      },

PHP:

 <?php
$request = "https://www.kimonolabs.com/api/5bwvka8s?apikey=*****&kimmodify=1";
$response = file_get_contents($request);
$results = json_decode($response, TRUE);

foreach($results['results']['collection2'] as $collection) {
    echo "<a href='" . $collection['property11']['href'] ."'>" . $collection['property11']['text'] . "</a><br >";
}



?>

Problem solved!

    
asked by anonymous 10.07.2015 / 16:00

2 answers

2

In the example you reported the collection2 is a vector, then as you passed an "index" that does not exist it will not bring the text.

  

Note: You are also printing the wrong variable, below the solution

<?php

$request = "https://www.kimonolabs.com/api/5bwvka8s?apikey=****&kimmodify=1";
$response = file_get_contents($request);
$results = json_decode($response, TRUE);


    echo $results ['results']['collection2'][0]['property11']['text'];



?>

The vector value [0] can contain more than one result, so consider using a foreach to go through all

  

Example

<?php
$request = "https://www.kimonolabs.com/api/5bwvka8s?apikey=****&kimmodify=1";
$response = file_get_contents($request);
$results = json_decode($response, TRUE);

foreach($results['results']['collection2'] as $collection) {
    echo $collection['property11']['text']."<br />";
}
    
10.07.2015 / 17:16
3

The problem is that collection2 will become an array (at least in the example of that URL you passed)

Then try to traverse this array

Ex.

<?php

$result = file_get_contents("https://www.kimonolabs.com/api/5bwvka8s?apikey=****&kimmodify=1");

$json = json_decode($result, true);

foreach($json['results']['collection2'] as $collection) {
    echo $collection['property11']['text'];
    echo "<br>";
}
    
10.07.2015 / 16:26