Mr Sorbose
Mr Sorbose

Reputation: 777

How to display specific json values rather than print or dump function

using the following, I can display all information as an array in two formats, however I wish to assign a value to a variable and use e.g just the names rather than a complete screen dump.

$url = 'http://myurl';

$json = file_get_contents($url);

$dump=(var_dump(json_decode($json, true)));

$json_output = json_decode($json); print_r($json_output)

This is probably very easy, my apologies.

Upvotes: 2

Views: 20319

Answers (3)

Matthew
Matthew

Reputation: 154

Using PHP's json_decode() function should satisfy this. In your first call, you pass TRUE as second parameter, so the function returns an associative array. The PHP manual page illustrates this difference:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));

These two calls to var_dump will output:

object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}

array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}

In either of these cases you can access the individual elements:

$json       = '{"url":"stackoverflow.com","rating":"useful"}';

$jsonAsObject   = json_decode($json);
$jsonAsArray    = json_decode($json, TRUE);

echo $jsonAsObject->url . " is " . $jsonAsArray['rating'];

This will output:

stackoverflow.com is useful

Upvotes: 1

Husman
Husman

Reputation: 6909

You use an Object oriented dot.notation to access variable names. Try something like this:

alert($json_output->varName);
alert($json_output['varName']);

Upvotes: 0

Dale
Dale

Reputation: 10469

You can use:

$object = json_decode($json);

This will create an object which you could then access the properties of like such..

echo $object->whatever;

Or you can use json_decode like this:

$array = json_decode($json, TRUE);

This create an array which you can access the indiviual keys of like so..

echo $array['whatever'];

Upvotes: 8

Related Questions