I have a request to the Facebook Graph API that returns a post from a facebook account.
I am simply trying to access the data instance of the object returned in PHP but everything I have tried returns NULL.
Sample response
{
"data": [
{
"id": " 111111111111111111100000",
"message": "Coming soon #PERFECTFIT 05.07.17 👀\nRegister to be one of the first to find out what it is here ⬇️\nhttp://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"created_time": "2017-06-26T17:39:20+0000",
"link": "http://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"full_picture": "https://scontent.xx.fbcdn.net/v/t39.2147-6/19284954_1592534984092755_4946207882807869440_n.jpg?oh=56cc96435f423cec31962966b6f689c2&oe=59DB08B6"
}
]
}
I want to get at the array of objects data provides so I can MVC the data returned in a larger response.
This doesn't currently work:
$response->data; // returns null
$response[0]->data; // returns null
$response->data[0]; // returns null
Feel I'm missing something obvious.
first decode it with json_decode then trying to access the data object
$res = json_decode($response);
print_r($res->data);
print_r($res->data[0]->id);
print_r($res->data[0]->message);
code
you have to use first json decode function so you can get the data from the json response.
$response = '{
"data": [
{
"id": "143384725674462_1592535354092718",
"message": "Coming soon #PERFECTFIT 05.07.17 👀\nRegister to be one of the first to find out what it is here ⬇️\nhttp://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"created_time": "2017-06-26T17:39:20+0000",
"link": "http://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"full_picture": "https://scontent.xx.fbcdn.net/v/t39.2147-6/19284954_1592534984092755_4946207882807869440_n.jpg?oh=56cc96435f423cec31962966b6f689c2&oe=59DB08B6"
}
]
}';
$response = json_decode($response);
print_r($response->data[0]->id);
print_r($response->data[0]->message);
Related
I'm getting a JSON response from an API provider which I can't change, and there are lots of nested objects in the response and then there is an object which I need, below is just the example of response actual response has a lot of nested objects and then the match object,
I can easily access the match object but in some case, the API provider add some more object above it as shown in the 2nd response where he added the group and then there is match object which I need,
still by using some if, else we can get through it.
but are there any methods or ways available that can directly give me access to the match object or can find the match object?
I'm using laravel 5.8
and tried some of the collection methods none of them work on objects.
in actual response, I have to go 7 steps nested.
//1nd API response
[{
"version": "2.258.2",
"sport": "badminton",
"lang": "en",
"generated_utc": "2021-07-28T13:58:16+00:00",
"method": {
"method_id": "258",
"name": "get_matches"
"match" : {
score_a:0,
score_b:1
}
}
}]
//2nd API response
[{
"version": "2.258.2",
"sport": "badminton",
"lang": "en",
"generated_utc": "2021-07-28T13:58:16+00:00",
"method": {
"method_id": "258",
"name": "get_matches"
"group":{
"match" : {
score_a:0,
score_b:1
}
}
}
}]
Thank You!
I am trying to the balance in a PHP object, I tried everything but am getting array to string conversion error, here is the string
{
"status": true,
"message": "Balances retrieved",
"data": [
{
"currency": "NGN",
"balance": 0
}
]
}
its a response from a remote server, i am trying to get the balance, i tried
$response->data->balance
json_decode($response)->data->balance
json_decode($response[0])->data->balance
but none of them worked, the response from the remote server is stored in a variable called $response
How can i get the balance from the response
Data is an array
json_decode($response)->data[0]->balance
Take a look at this example, that I created: http://sandbox.onlinephpfunctions.com/code/414f23b1a09221ed5bd7f299f5eb73a2f9f932b1
First you decode the JSON string
Then access data array at the index 0, so data[0]
And then data[0]->balance, access object property 'balance'
Gerard's answer is right.
Also you can naviguate the result of a json_decode function in array mode.
<?php
$json = '{
"status": true,
"message": "Balances retrieved",
"data": [
{
"currency": "NGN",
"balance": 0
}
]
}';
$response = json_decode($json);
echo $response["data"][0]["balance"];
echo $response->data[0]->balance;
Using a variable to register the decode answer will save you time.
I'm working with the Zoho CRM. The response format I get from their API seems a bit odd to me; I can't just pull an object from it like I would normally. I'm trying to parse the results using PHP. Here's an example of their response formatting:
{
"response": {
"result": {
"SalesOrders": {
"row": {
"FL": [
{
"content": "6666666000000000000",
"val": "SALESORDERID"
},
{
"content": "Order",
"val": "Subject"
},
{
"content": "Pending",
"val": "Status"
},
{
"content": "John Smith",
"val": "Order Owner"
},
{
"content": "Canada",
"val": "Billing Country"
},
{
"product": {
"FL": [
{
"content": "5555555000000000000",
"val": "Product Id"
},
{
"content": "Roller Coaster",
"val": "Product Name"
}
],
"no": "1"
},
"val": "Product Details"
},
"content": "Pending",
"val": "Ticket Status"
}
],
"no": "1"
}
}
},
"uri": "/crm/private/json/SalesOrders/getRecordById"
}
}
What I'm trying to do is get the Product ID of the Product (in this case the value is "5555555000000000000".
Every response has the same structure, but I can't use the index to parse out the key/value because the amount of fields could change between API calls (meaning the index of product could be 5, like above, or 7, or 8, or whatever depending on the amount of fields being pulled in). I don't understand why they didn't use typical key/value pairs, such as "Product_ID": "5555555000000000000" which would make all of this a non-issue.
Is there a way to do this without iterating through every key/value pair looking for a "val" of "Product ID" and then grabbing the associated "content" (which is the product id I'm looking for)? That's the only way I could think of and it doesn't seem very efficient.
PHP has a function for that: json_decode. See http://php.net/manual/en/function.json-decode.php
$response = "... your JSON response from wherever ...";
$data = json_decode($response, true);
// Access the nested arrays any way you need to, such as ...
$orders = $data["response"]["result"]["SalesOrders"];
foreach ($orders["row"]["FL"] as $item) {
if (array_key_exists("product", $item) {
echo $item["product"]["FL"][0]["content"];
}
}
EDIT: Corrected 2nd arg to json_decode (thanks Marcin)
I don't understand why they didn't use typical key/value pairs, such as "Product_ID": "5555555000000000000" which would make all of this a non-issue.
Yes, there could be a key=>value pair, but that would be to easy.
Because Zoho ... ;)
Is there a way to do this without iterating through every key/value pair looking for a "val" of "Product ID" and then grabbing the associated "content" (which is the product id I'm looking for)?
No, (even if you turn this into an array using json_decode($data, true) and go forward by using named keys) you end up iterating or testing for key existence (need to get to product-FL-val to get product-FL-content). Maybe array_fiter or array_walk with a callback come to rescue, but they also iterate internally.
My suggestion is to simply safe some time and use an existing package, e.g.
https://github.com/cristianpontes/zoho-crm-client-php
or search one on Packagist https://packagist.org/search/?q=zoho
I dont know this might help or not. But this is what i am using for my Zoho APP. Actually I am developing a PHP app using Zoho. Your JSON and mine is same but i am getting Deals and you are fetching SalesORders.
<?php
$token = $_SESSION['token'];
$url = "https://crm.zoho.com/crm/private/json/Deals/getRecordById?authtoken=$token&scope=crmapi&id=$dealID";
$result = file_get_contents($url);
$deal_detail = json_decode($result);
$deal_detail = json_decode(json_encode($deal_detail), True);
$deal_detail_array = array();
//Instead of Deals you have SalesOrder right
foreach($deal_detail['response']['result']['Deals']['row']['FL'] as $array){
$deal_detail_array[$array['val']] = $array['content'];
}
echo $deal_detail_array['DEALID']; // You can change this to SALEORDERID, get data correctly every time.
echo $deal_detail_array['Deal Name'];
echo $deal_detail_array['Amount'];
///.......and so on ..............//
//................................//
Only the difference between your JSON and mine is: You have "SalesOrders" in your JSON after result field and in my json instead of SalesOrders i have Deals there.
this code is working fine for me. SO you can do same thing except a field update. I am getting DEALID correctly for each request similarly you can get you SALESORDERID
I am trying to retrieve all records and display them in a JSON file.
My current function retrieves all Events that belong to a specific user.
/**
* create json files from doctrine/mongo
* #Route("/createjson", name="createjson")
*/
public function createJson()
{
// check user authentication
$this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');
$dm = $this->get('doctrine_mongodb')->getManager();
$repository = $dm->getRepository('AppBundle:Event');
$events = $repository->findBy(array('user' => $this->getUser()));
$serializer = SerializerBuilder::create()->build();
$result = $serializer->deserialize($events, 'AppBundle\Document\Event', 'json');
var_dump($result);
exit;
}
This is not working because some of the elements passed into the serializer are of an array format. Error I am getting.
Warning: json_decode() expects parameter 1 to be string, array given
500 Internal Server Error - ContextErrorException
However if I use the inbuilt Symfony Serializer it works fine:
$serializer = $this->container->get('serializer');
$reports = $serializer->serialize($events, 'json');
return new Response($reports);
However the JSON to be produced will be different to my Document/Entity hence why I want/need to use the JMSSerializerBundle.
For example, a record looks like this:
[{
"id": "572041b3288b560e5e00451c",
"name": "Test",
"date": "2016-04-27T05:25:00+1000",
"enddate": "2016-04-30T11:55:00+1000",
"location": {
"name": "Sydney, NSW"
},
"key": {
"id": "1g43g34g34g23f32g32G32gGSDF"
},
"user": {
"id": "57203174288b560e5e0044da"
}, ...
}]
But I only want to display (output) to JSON
[{
"id": "572041b3288b560e5e00451c",
"name": "Test",
"date": "2016-04-27T05:25:00+1000",
"location": "Sydney, NSW"
}]
How would I go about doing this? There is not much documentation on JMSSerializerBundle online.
Edit: I should mention that the database collection I am querying has a relation to the User collection which is managed by FOSUserBundle. I'm not sure if this has any relation to my problem however
You should look at the documentation of the bundle, may be you will find more information
http://jmsyst.com/bundles/JMSSerializerBundle
http://jmsyst.com/libs/serializer/master/usage
You seems to use the wrong function of the serializer. In your case, you seems to need to get a json from your user object, so you need to use
$serializer = SerializerBuilder::create()->build();
$result = $serializer->serialize($events, 'AppBundle\Document\Event', 'json');
serialize($object):string : get a string from an object
deserialize($string):object : get an object from a representation of an object (json, xml...).
I am currently working to parse through FB api data. Take the following for example...
{
"data": [
{
"id": "ID",
"name": "Creative!"
},
{
"id": "ID",
"name": "a name"
}
],
"paging": {
"cursors": {
"after": "fdsagfsganhdfs==",
"before": "gfdwiolrukjhteqrfgbh"
}
},
"summary": {
"total_count": 2
}
}
This is an example of what is returned when the Graph API is queried for likes. The issue I am having is that I want a clean way to get the total_count out of this data. Often times it will come in without the summary field if there are no 'likes'. This is easily parsed by doing a few if isset() and if array_key_exists but I will be dealing with a lot of data and this use case applies to many different type of data from FB. Any advice on just getting the total_count field? FQL would work but seems to be deprecated. Thanks.
If the total_count field is in fact the sum of the number of elements in the data array then you can simply use the count function in PHP to count the length of the array.
$json_array = json_decode($fb_json_string, true);
$total_count = (isset($json_array['total_count']))? $json_array['total_count']:((isset($json_array['summary']['total_count']))? $json_array['summary']['total_count']:0);
I don't know if I can make it any uglier, it's simply a suggestion though.