Getting Json to work in PHP

How do you access info from inside a json feed when it is not at the top level?

[php]function test_func( $atts ){
$json = file_get_contents(‘https://affiliate.creditkarma.com/api/v1/offers/card/CCAmericanExpressCard54-json?pubKey=JIA7EF9VEK5X0R5J’);
$obj = json_decode($json);
return $obj ->{‘status’};
}[/php]

This works and spits back “SUCCESS” which is what is in there for status. But I am trying to get at something that is another level or two in.

For example, let’s say I want what’s in the “Name” filed inside the “Header” heading? I have tried a bunch of ways such as:
[php]return $obj ->{‘header.name’};
return $obj ->{‘name’};
return $obj ->{‘header(‘name’)’};
[/php]

But none of them returned anything.

Site: acq1.com/f
Feed I am trying to access: https://affiliate.creditkarma.com.com/api/v1/offers/card/CCAmericanExpressCard54-json?pubKey=JIA7EF9VEK5X0R5J

Thanks!!!

Try[php]return $obj->{‘header’}->{‘name’};[/php]

You could also set the json_decode assoc flag to return a regular php array. This would look like this:[php]function test_func($atts)
{
$json = file_get_contents(‘https://affiliate.creditkarma.com/api/v1/offers/card/CCAmericanExpressCard54-json?pubKey=JIA7EF9VEK5X0R5J’);
$obj = json_decode($json,true);
return $obj[‘header’][‘name’];
}[/php]

Let me know if these don’t work for you…

This has helped a lot. Thank you.

I have realized as I read further down the json code, that there is an extra “[” inbetween two levels of nesting that won’t let me use your method to get at the info that I really care about.

[code]{
“header”:{
“name”:“Credit Karma Affiliate Network”,
“version”:1
},
“status”:“SUCCESS”,
“offers”:[
{
“id”:“CCAmericanExpressCard54”,
“title”:“Blue Cash Everyday(SM) Card from American Express”,

[/code]
I truncated, but the link is above.

so,

[php]return $obj->{‘header’}->{‘name’};[/php] works

[php]return $obj[‘offers’][‘title’];[/php] doesn’t work

I assume it is that extra “[”

Any thoughts on how I bypass the “[”?

thanks!

If you are using the assoc flag it would be: $obj[‘offers’][0][‘title’]

If you are not using the flag: $obj->offers[0]->title;

Let me know if these don’t work.

It didn’t seem to work, but I didn’t mess around too much since I found an alternative work around. Though I am wondering if the workaround will add too much overhead to the website?

[php]function ck_func($atts, $content = “defaultvalue”){

//This extracts the type field from what is being passed inside the brackets in the shortcode. It is an array so you can pass multiple things. You would just add them below under type.
extract( shortcode_atts( array(
‘type’ => ‘sampledefaulttype’,
), $atts ) );

//this puts the contents of the URL into a string note the dollar sign and what follows, that takes what is passed in the middle of the short code and includes it as part of the link.
$jsonbad = file_get_contents(“https://affiliate.creditkarma.com/api/v1/offers/card/$content-json?pubKey=9LJJ2TMZ3WE9M923”);

//the following strips out an open and close bracket in ck’s json code that seems to cause problems
$jsonstillbad = str_replace(’“offers”:[{’, ‘“offers”:{’, $jsonbad);
$json = str_replace(’}}]}’, ‘}}}’, $jsonstillbad);

// the following puts the decoded json into the obj string
$obj = json_decode($json,true);

//the following returns the text back to the wordpress page. It first checks for two specific types that are nested deeper. If it finds those it sends them back manually. Otherwise, it sends back whatever type is in the 2nd level of nesting.
if ($type == “long”) {
return $obj[‘offers’][0][‘summary’][‘long’];
} elseif ($type == “short”) {
return $obj[‘offers’][0][‘summary’][‘short’];
} else {
return $obj[‘offers’][0]["$type"];
}

}
add_shortcode( ‘ck’, ‘ck_func’ );[/php]

BTW, is it better to use the array method or the other method for efficiency?

Also, will json requests be automatically cached or should I do something to make this more efficient? My plan is to extract 3 or 4 types of data from 20 different json uri’s on my homepage. If this doesn’t cache automatically, I would guess the overhead would be high. I am using a wordpress plugin to cache the page, though I am not sure if that helps this situation. Is there an easy way to pull down the 20 json pages once a day or is that whole extra level of programming complication that will go over my head?

Thanks!

It’s weird that it doesn’t work for you. Using this code:[php]function test_func($atts)
{
$json = file_get_contents(‘https://affiliate.creditkarma.com/api/v1/offers/card/CCAmericanExpressCard54-json?pubKey=JIA7EF9VEK5X0R5J’);
$obj = json_decode($json);
return $obj->offers[0]->title;
}

echo test_func(0);[/php]

I get the following:Blue Cash Everyday(SM) Card from American Express

As I understand it, the server will not cache files and that is what I believe it considers the url to be in this case.

Others may have a better approach for you, but one possibility would be to write a script that gets the data from each of your pages and inserts it into a database table. You could setup a cron job to execute daily and then just pull all of the data from a single query whenever you need it. You could store all of the data returned from each page, or just some of the elements. Depending on your interests, you could store each new day’s data as a new row and be able to track historical changes.

As to which is more efficient, I really wasn’t sure myself. I ran the following test to find out: I iterated through each method 100,000 times. I wanted to ensure that I accounted for the possibility that the different calling methods (assoc true versus false) might result in different processing times, so I included the json_decode and retrieved the title during each iteration. Here are the actual results of the two methods:
Using the object method: 100,000 iterations took 10.52086687088 seconds.
Using the array method: 100,000 iterations took 9.0901169776917 seconds.

As you can see, the array method appears to be faster, but the average difference per use is a mere 0.0000143 seconds.

I used the following methods for obtaining the title:[php] $obj = json_decode($json);
$title = $obj->offers[0]->title;
[/php]
and[php] $obj = json_decode($json, true);
$title = $obj[“offers”][0][“title”];[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service