1

Possible Duplicate:
How to decode a JSON string in PHP?

I would like to extract the variable 'name' from the json string $jsonstring;

<?php

$facebookid = $_GET['fbid'];
$facebooklink = 'http://graph.facebook.com/'.$facebookid.'?fields=name';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $facebooklink);
curl_setopt($ch, CURLOPT_HEADER, 0);
$jsonstring = curl_exec($ch);
curl_close($ch);

?>

$jsonstring would output something like the following:

{
   "name": "THIS PART IS WHAT I WANT",
   "id": "4"
}

I would like to extract the 'this part is what i want' from the above example.

I have tried using json_decode but couldn't get it working, I have since deleted that code and therefore cannot write it here. Thanks for any help.

1
  • $jsonstring = curl_exec($ch); will not give you assign of json. It just gives you status of curl_exec Commented May 22, 2012 at 17:14

5 Answers 5

3

try

ob_start();
$facebookid = $_GET['fbid'];
$facebooklink = 'http://graph.facebook.com/'.$facebookid.'?fields=name';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $facebooklink);
curl_setopt($ch, CURLOPT_HEADER, 0);
$jsonstring = curl_exec($ch);
curl_close($ch);
$bufferstr = ob_get_contents();
ob_end_clean();
$json = json_decode($bufferstr);
echo $json->name;
Sign up to request clarification or add additional context in comments.

5 Comments

@Andreas & OP - Thanks for the replys - However every answer returns the same thing: {"name": "THIS PART IS WHAT I WANT","id": "4"} without the 'name' extracted, I don't know what I'm doing wrong? :s Thanks.
@Harry any error? any output echoing or doing var_dump?
I know its a lot to ask, but you would be doing me a massive, massive favour if you could quickly look over my code? I'd be extremely grateful, I have uploaded the .php file to here: dl.dropbox.com/u/2578642/facebookconf.php Thank you
@Harry It was because $jsonstring didn't give you content of json. It is just status that curl_exec was success. Look at my edited post. I use buffer to catch the json string.
I thank you so, so much! Its working now - you've helped me out greatly! Thanks again :D
1

Try:

<?php
  $foo = json_decode( $jsonstring);
  $name = $foo->name; 
  //echo $name;
?>

Comments

1

try this

$json_obj = json_decode($jsonstring );
echo $json_obj->name; 

Comments

0
<?php
    $json = '{"foo-bar": 12345}';

    $obj = json_decode($json);
    print $obj->{'foo-bar'}; // 12345
?>

Comments

0

In the case that you do not have "json_decode" in your php version you should use a regular expression.

<?php

$name = json_decode( $jsonstring )->name;

?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.