Ben Potter
Ben Potter

Reputation: 875

Turn JSON script URL into variables in PHP

I was wondering how on earth to get a json string into php.. here's my string:

(go here) http://urls.api.twitter.com/1/urls/count.json?url=http://www.onewiththem.com.au/&callback=twttr.receiveCount

and you should see this returned:

twttr.receiveCount({"count":0,"url":"http:\/\/www.onewiththem.com.au\/"});

I was wondering how to get the count number and have it set up in the variable $count ?

Upvotes: 1

Views: 362

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173522

Simple, using json_decode() and file_get_contents():

$data = json_decode(file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=http://www.onewiththem.com.au/'));
echo $data->count;

Note that I removed the &callback= from the URL, because that's only used for JSONP and PHP doesn't need it.

Upvotes: 2

xdazz
xdazz

Reputation: 160833

If you mean get it in javascript, then the data in your callback function is the object. You could get the count just by data.count.

twttr.reciveCount = function (data) {
  console.log(data.count);
  // do the rest
}

If you call the api from php, then you should not use the callback parameter. Get the JSON response and then use json_decode to decode it. (Don't forget urlencode the url parameter.)

$response = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url='.urlencode('http://www.onewiththem.com.au/'));
$json = json_decode($response);
echo $json->count;

Upvotes: 0

Related Questions