PHP & json_decode - how to get property of object - php

CONTEXT
I'm using json_decode to convert the contents of an Facebook open graph call into a php object.
EDIT to add code
My code looks like this:
$json = json_decode(file_get_contents("http://graph.facebook.com/http://example.com"),true);
var_dump($json);
A var_dump of the resulting object looks like this:
ARRAY(3) { ["ID"]=> STRING(18) "HTTP://EXAMPLE.COM" ["SHARES"]=> INT(14604317) ["COMMENTS"]=> INT(11300) }
PROBLEM
I would like to get the 12 from this object. I assumed that $json->shares would return 12, but instead it returns null. Any idea what the correct syntax for retrieving the 12 would be?

Your array doesn't look right. Check out http://graph.facebook.com/http://example.com in a browser, notice how the keys and values are all lowercase, not uppercase like you have.
If you really are testing http://graph.facebook.com/http://example.com, then this will just work:
$array = json_decode(file_get_contents('http://graph.facebook.com/http://example.com'), true);
echo $array['shares'];
This gives me 14604317 which I can see in my browser is the correct result.
Note you have an array, not an object. So use array notation:

Related

Uncaught Error: Cannot use object of type stdClass as array

Fatal error: Uncaught Error: Cannot use object of type stdClass as array
$code = json_decode($src);
echo $code["items"];
var_dump shows the following (truncated):
object(stdClass)#7 (3) { ... }
I don't know what stdClass is and how to use it.
Edit:
stdClass is a class which creates an instance of simple object. Properties of classes are to be accessed using ->, not [...] notation.
As per documentation for json_decode, simply setting the second argument to true will result in the result being associative array, which can be in turn accessed like an array.
At the time of posting this question, I didn't try searching on how to decode JSON - as that's pretty simple and I got that working. I was just getting another error (above), and had no luck searching on how to fix that. I believe people have similar problems, as this question is getting some views as well.
Use json_decode($src, true) to get associative array.
This is preferred way, as currently you get mixed arrays and objects and you may end up in crazy house, trying to work with these :)
Alternatively use -> operator to get properties of object.
Currently your item is at:
$code->items[0]->pagemap->cse_image[0]->src
The json_decode function has a second parameter dedicated to just that: setting it to true will return an associative array where there is an object (in { "curly": "braces" }) in JSON.
To illustrate that:
$a = json_decode('{ "b": 1 }', false);
var_dump($a->b);
// prints: int(1)
$a = json_decode('{ "b": 1 }', true);
var_dump($a['b']);
// prints: int(1)
Note the difference in how values are accessed.
Further reading: http://php.net/json_decode

Access Json Object PHP (String Not Array)

Yes, I have read previous questions and I know how to access a JSON object and how to convert it into an array. I know about json_encode/decode. My problem is that my JSON response has a string, arrays and all and it will always return NULL when I access the data directly.
object(Unirest\Response)#8 (4) {
["code"]=>
int(200)
["body"]=>
string(666) "{ "ticker": "AAPL:US", ".."
["headers"]=>
array(9) {
[0]=>
string(15) "HTTP/1.1 200 OK"
Normally you would be able to directly access the object like this and this worked just fine when I last accessed the script a few days ago:
$response->body->ticker
Or you could use json_decode with true to turn it into an array.
$array = json_decode($response->body, true);
However, all of this no longer works. I believe they changed something with the output because it was working just a while ago but I have no clue. Any idea how to access the ticker data? I tested it with a different API and the same commands are working just fine to retrieve data from a different API, but the output seems to be different.
$response->body is a json string assuming you didnt shorten it so much as to loose someting important and therefore needs to be seperately converted to a PHP data item.
As its a json string representing an object why not convert it to a PHP object like so
$body = json_decode($response->body);
Then you can address its properties like
$body->ticker
Alternatively
$response->body = json_decode($response->body);
Now you can address it as you expected i.e.
$response->body->ticker
Ok, finally solved it after reading this answer:
PHP json_decode() returns NULL with valid JSON?
Apparently, as I assumed earlier it was a formatting issue. I did not know that JSON would return NULL if the object includes non-UTF8 code and/or BOM codes.
I couldn't find any BOM codes but I suppose there was some non-UTF8 that was breaking it.
Long story short this works:
$dec = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $response->body), true );
echo $dec['ticker'];
Well at least I now know a lot more about JSON which will come in handy some day ;)

Cant get value in PHP array but var_dump shows that it exists

Long time, my PHP-application ran on a linux server with apache and PHP.
Now I've set up a windows server with apache and php and simple PHP-Programs have problems.
var_dump($data);
die(var_dump($data['a']));
results in
object(stdClass)#1 (1) { ["a"]=> string(1) "b" }
Fatal error: Cannot use object of type stdClass as array in BLUB.php on line 14
var_dump says there is an index a. Why does $data['a'] throw an exception?
EDIT: $data is json_decode($something);
Because its an object, not an array. You cant access it like that. This would be correct:
$data->a;
The error contains your answer - $data is actually an object of type stdClass. You could either:
a) access the property 'a' with $data->a
or
b) typecast $data as an array using (array)$data
You should use:
$data = json_decode($something, true);
To get array from json
As the error says $data is an object, not an array. As such, you want to use object access, rather than array access. In this case, that would be var_dump($data->a)
since $data in an object you have to access it this way:
$data->a;
Otherwise, you can typecast it to an array and access it actually like an array
$dataArr = (array) $data;
$dataArr['a'];
NOTE
This is possible only whether your object attributes are public

Retrieve value from an object

I have an object and like to retrieve the value of one or more elements from the object. Hire is one of the objects if put in a var_dump().
object(SimpleXMLElement)#13 (2) {
["#attributes"]=>
array(1) {
["name"]=>
string(5) "chain"
}
["value"]=>
string(11) "Abba Hotels"
}
I get the value but i can not get to the name.
To get the value i use for example:
echo $row->property->value
My first thought was to use:
echo $row->property->#attributes->name
, but it return as a ERROR. I try to use #attributes in a variable but that gives a NULL.
At second thought i tried to use get_object_vars() and in_array() but no luck again.
Do you guys have a idea about how i can get to the value of the "name" object?
See the docs for SimpleXMLElement:
$object->attributes()
Will give you what you need. I.e.
echo $object->attributes()->name;
It looks like you are using a property value from somewhere. If $row is the object, then you could use this I think.
$row->#attritubes['name']
Im not fully sure but thought id give it a go helping anyawy. Let me know if it works.

Facebook Stream.Get -- How to access data in array?

On stream.get, I try to
echo $feeds["posts"][$i]["attachment"]["href"];
It return the URL, but, in the same array scope where "type" is located (which returns string: video, etc), trying $feeds["posts"][$i]["attachment"]["type"] returns nothing at all!
Here's an array through PHP's var_dump: http://pastie.org/930475
So, from testing I suppose this is protected by Facebook? Does that makes sense at all?
Here it's full: http://pastie.org/930490, but not all attachment/media/types has values.
It's also strange, because I can't access through [attachment][media][href] or [attachment][media][type], and if I try [attachment][media][0][type] or href, it gives me a string offset error.
["attachment"]=> array(8) {
["media"]=> array(1) {
[0]=> array(5) {
["href"]=> string(55) "http://www.facebook.com/video/video.php?v=1392999461587"
["alt"]=> string(13) "IN THE STUDIO"
["type"]=> string(5) "video"
My question is, is this protected by Facebook? Or we can actually access this array position?
Well, once the data is returned to you, it can no longer be protected by Facebook. You have full access to everything in that result as a regular data structure.
From the looks of it, there are multiple href properties throughout, so you'll want to be careful which one you're going for. $feeds["posts"][$i]["attachment"]["href"] is a valid element for some items, but $feeds["posts"][$i]["attachment"]["media"][0]["href"] is also a valid element.
There doesn't appear to be a $feeds["posts"][$i]["attachment"]["type"] element though, so that's why you're getting nothing for that particular item. There is a type inside ["attachment"]["media"][0] however, which is probably what you want.
If you are getting a string offset error when using array syntax, you've probably mixed up an element somewhere. Strings can be accessed via array syntax. For example:
$str = "string";
echo $str[1]; //echos 't'
You would get an offset warning if you tried to access an index that was larger than the string. In any case, from the looks of that output, $feeds["posts"][$i]["attachment"]["media"][0]["type"] should work.

Categories