Aaron
Aaron

Reputation: 1976

PHP: Grab specific data from a JSON string

$url = "https://graph.facebook.com/fql?q=SELECT%20uid2%20FROM%20friend%20WHERE%20uid1=me()&access_token=sadfasdf";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 GTB5');
$string = curl_exec($ch); // grab URL and pass it to the browser
echo $string;
curl_close($ch);

Right now, echo $string outputs the entire data grabbed as plain text.

{ "data": [
    { "uid2": "91298391" },
    { "uid2": "00291509" },
    { "uid2": "101927261" }
]}

How can I instead grab specific data similar to JSON? In this case, I want to be able to grab every id. I have a feeling I will use preg_match but I'm stumped.

Upvotes: 0

Views: 289

Answers (1)

helloandre
helloandre

Reputation: 10721

php has a built in function for turning a json string into an array.

json_decode

the second parameter makes it give you back an assoc array instead of an object. Then just grab the values:

$ids = array_values(json_decode($string, true));

Upvotes: 1

Related Questions