Help printing readable JSON to screen via php api

Hi,

Basically i am currently developing a text messaging application that operates using an email to sms gateway. I have the app mostly built, but am currently stuck due to a lack of understanding on JSON.

Via an API on the email to sms gateway i am able to retrieve how many credits are currently left in the system and display it on my app. Currently, it looks something like this when echo’d to screen:

{“balance”:{“sms”:46,“mms”:0},“status”:“success”}

The thing is the only figure i require here is the “46”… I simply want to be able to echo the number of sms credits available to the screen rather than the whole json string. Can anyone help with how to do this?

Also, i would ideally like to be able to process this through PHP so that i can run if statements on how many credits are left, if ($credits<=1) {} for example

Hi jwallaceni, welcome to the forum,

That is JavaScriptObjectNotation
viewed another way

$response = {
             "balance": {
                          "sms":46,
                          "mms":0
                          },
           "status":"success"}

So what you want is $response.balance.sms

Where $response (or whatever you’ve named it) is an object with 2 properties, the first property, “balance” is an object with 2 properties, “sms” and “mms”

OK by the looks of it you have my situation down perfectly, the variable is called $response also. I have tried the following:

$response = $response.balance.sms;

echo $response;

But i still dont think im grasping it correctly. Is there a way to simply echo the figure without involving jquery?

You don’t necessarily need to use jQuery, but unless the API allows for a way to return only that you need to “drill down” to it somewhere.

You could use plain JavaScript to do this easily enough. Or if the JSON is going to a PHP file you could do it there and have PHP return only the value you’re interested in.

($response.balance.sms is not valid notation in PHP. . is the concatenation operator, not the member-selector.)

If you have $response as your string, [FPHP]json_decode[/FPHP] it, and then you can access it with standard PHP object notation: $object->balance->sms;

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.