Reputation: 1
i have searched and searched but i don't know where i'm wrong getting a value from JSON encode, can you help me? Please don't kill me, i'm a newbie :)
My php:
<?php
$data = json_decode("document.json", true);
$getit = $data["likes"];
My JSON:
[{
"title" : "MYTITLE",
"image" : "MYIMAGE",
"likes" : 0
}]
EDIT
Thanks for the help this is now working!
Upvotes: 0
Views: 2326
Reputation: 15629
json_decode
expects an string, not an filename - so you have first get the contents of the given file. This could be easily achieved with file_get_contents
.
Your current json structure contains an array(with currently only one element), which contains an object. So if you want the likes, you have to read the first element of the result array and of that(an associative array), the likes.
$data = json_decode(file_get_contents($filename), true);
$likes = $data[0]['likes'];
If you have more than one object in the given json file, you could loop over the data with foreach
foreach ($data as $element) {
echo "likes of {$element['title']}: {$element['likes']}\n";
}
Upvotes: 2
Reputation: 1792
Your JSON is an array of objects, you first need to access the first element of your array :
$data[0]
Then you can access the key you want :
$getit = $data[0]['likes'];
Plus, as stated in a comment above, you need to pass a string to json encode, here is an code sample that should suit your needs :
<?php
$data = json_decode(file_get_contents('document.json'), true);
$getit = $data[0]["likes"];
Hope this helps.
Upvotes: 0
Reputation: 8850
For json_decode
you have to pass JSON string, not a file name. Use file_get_contents
to get JSON content and then decode it.
$data = json_decode(file_get_contents('document.json'), true);
$getit = $data[0]['likes'];
Upvotes: 1