Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Other Retrieving, understanding and displaying a JSON feed on my site. (advice needed!) Re: Retrieving, understanding and displaying a JSON feed on my site. (advice needed!)

#108482
TheDoc
Member

My only experience is using jQuery for this, but I think it looks *very* similar in PHP.

I’ll give you an example of some code I use for Twitter’s API:

$.ajax({
url: 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=[twitterUserName]&count=20&callback=?&include_rts=true',
dataType: 'jsonp',
success: function(data) {
// do something with the data
// to see what the data is returning, you can log it to the console
// by going console.log(data);
},
error: function() {
// something is borked - display an error message
}
});

So you would replace [twitterUserName] with a username and you’d return a bunch of information in a file that looks like: https://api.twitter.com/1/statuses/user_timeline.json?screen_name=graygilmore&count=20&callback=?&include_rts=true

It might look all jumbled, but that’s just because the browser is putting it all together on one line. If you take that data and paste it into here: http://jsbeautifier.org/ you’ll see that it’s actually neatly sorted.

So let’s say we wanted to get some information from that call. Let’s try to find out how many people I’m following. Inside our success function I would do something like this:

var following = data[0].user.friends_count

We’re just following the chain of where that information lives. First object in the Data array > User > Friends Count. It’s pretty simple, really!

If we wanted to do something different for each tweet, we could do something like this:

$.each(data, function() {
// do something with each tweet
});