-1

Possible Duplicate:
Able to see a variable in print_r()'s output, but not sure how to access it in code

PHP code to parse json:

<?php
$url = "http://xxx.com/request-url?type=json";
$string = file_get_contents($url);      
$json = json_decode($string);

if (count($json)) {
  echo $json->book->title;
} else {
  echo "No book found";
}
?>

Example json response:

{"book":[{"title":"Good day"}]}

Because of single array, i've removed foreach: foreach($json->book as $books)

I tried:
$json->book->title,
$json->title,
$json[book][title],
$json[title].

All not working.

Any help?

Community
  • 1
  • 1
richard
  • 1,456
  • 4
  • 15
  • 22
  • just tried, not working. – richard Jan 05 '13 at 10:55
  • @richard: `print_r` is to show you how it is structured. You then *do* see how to access it. But better use `var_dump`, it gives more specific information. If nothing helps, you need to provide the [hexdump of the Json string](http://stackoverflow.com/questions/1057572/how-can-i-get-a-hex-dump-of-a-string-in-php). – hakre Jan 05 '13 at 10:55

1 Answers1

3

When you do print_r($json) you get

stdClass Object
(
    [book] => Array
        (
            [0] => stdClass Object
                (
                    [title] => Good day
                )

        )

)

You access StdClass properties with -> and arrays with []

So, obviously, it's

$json->book[0]->title;

Click for Demo

If this is not working, then your JSON is likely invalid. Check it with http://www.jsonlint.com

Gordon
  • 312,688
  • 75
  • 539
  • 559