Sam Bronson
Sam Bronson

Reputation: 69

Parse JSON from URL with PHP and JS

I receive a json with data from URL (this is celery's flower plugin). Sample:

{
  "celery@s1": {
    "scheduled": [],
    "stats": {
      "clock": "2535550",
      "pid": 26002,
      "broker": {
        "transport_options": {},
        "login_method": "AMQPLAIN",
        "hostname": "127.0.0.1",
        "alternates": []
      },
      "prefetch_count": 8,
      "total": {
        "stone": 2602,
        "wood": 34
      }...

I try to parse it and make custom statistics page using PHP and JS.

Parsing with php:

<?php 
$url = 'http://127.0.0.1:5555/api/workers';
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach($json['celery@s1']['stats']['total'] as $item) {
    echo json_encode($item['wood']);
}

?>

And JS which gets data from php script with an update timer:

function getFromFile() {
    $.get("s_updater.php",function(response) {
        response = JSON.parse(response);
        console.log(response)
        $("#field-1").html(response);
    });
}

$(document).ready(function() {
    var period = 1000;
    getFromFile();
    var per = setInterval(function() {
        getFromFile();
    }, period);
});

But looks that I made a mistake somewhere and now I'm stuck. And is there maybe any better way to do this? All I want is to get "wood":34 from URL's json and show value on a html page.

Upvotes: 2

Views: 778

Answers (2)

Isuranga Perera
Isuranga Perera

Reputation: 510

$json = json_decode($content, true);

 echo $json['celery@s1']['stats']['total']['wood'];

You don't have to use a loop or JSON to send a single value just echo it.

JS Code

function getFromFile() {
    $.get("s_updater.php",function(response) {
        console.log(response)
        $("#field-1").html(response);
    });
}

Upvotes: 1

Mr_KoKa
Mr_KoKa

Reputation: 618

TL;DR To get wood value you would need to access it by $json['celery@s1']['stats']['total']['wood']

When you are iterating $json['celery@s1']['stats']['total'] you will get two $items, but those items are integers, not arrays: 2602 for stone and 34 for wood. PHP should notice you about that.

To visualize it some more if you do

foreach($json['celery@s1']['stats']['total'] as $key => $item) {
    echo $key.': '.$item;
}

You would get:

stone: 2602

wood: 31

To get wood value you would simply do $json['celery@s1']['stats']['total']['wood'] and decode it as json or output it as a number. When you echo it as number then don't do not expect json at JS side.

Upvotes: 1

Related Questions