How do I access deeper levels of a json tree using curl? - php

I'm trying to learn how to use CURL and Json to access data sent from the Facebook graph api.
I'm using the following function which pulls the post data:
function loadFB($fbID){
$url="https://graph.facebook.com/".$fbID."/feed?limit=1&access_token=xxxx";
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$page = json_decode(curl_exec($c));
curl_close($c);
$post=reset($page->data);
if($post->message == '') {
$post_msg = '' . $post->name . '';
} else {
$post_msg = $post->message;
}
return $post_msg;
}
Example JSOn data looks like this:
{
"data": [
{
"id": "xxxx",
"from": {
"name": "xxx",
"category": "xxx",
"id": "xxx"
},
"picture": "xxxxxxxxx",
"link": "xxxxxxx",
"name": "Event name goes here",
"properties": [
{
"text": "Friday, July 15, 2011 at 4:00pm"
},
{
"text": "Venue Name"
}
],
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yW/r/r28KD-9uEMh.gif",
"type": "link",
"object_id": "xxx",
"created_time": "2011-06-23T06:46:17+0000",
"updated_time": "2011-06-23T06:46:17+0000",
"likes": {
"data": [
{
"name": "xxxx",
"category": "xxx",
"id": "xxxx"
}
],
"count": 1
}
}
],
"paging": {
"previous": "xxxxx",
"next": "xxx"
}
}
As it stands, I can retrieve the message of a page update, or if its an event I can retrieve the event name and the link for the event.
But what if I want to retrieve say the event date or the venue name? Its under another tier of 'properties'.
With my code so far, I can access the first level of things with $post->message, but when I try $post->properties->text this doesn't work - so I don't understand how this works. On top of that, in the 'properties', there's 2 'text' which is adding to my confusion of how to access these things.
Any pointers?

$post->properties is an array so :
$post->properties[0]->text;

Properties in the data above is an INDEXED ARRAY so you want $post->properties[x].text where x is 0 for the first item and 1 for the second item, etc...

Related

How to replace JSON key without losing its value and position using PHP

This is the JSON
{
"table-name": "Kiwi",
"created-on": "November 20, 2021",
"columns": {
"Info": {
"type": "longtext",
"extra": ""
},
"Status": {
"type": "droplist",
"extra": ""
},
"Task": {
"type": "text",
"extra": ""
}
},
"data": [
{
"Name": "Team Reports",
"Info": "Submitting marketing materials reports",
"Status": "Completed"
},
{
"Name": "Fabia HR",
"Info": "Brian asking for a report",
"Status": "Pending"
},
{
"Name": "Fabia",
"Info": "Meeting with CEO #cafe 9:00",
"Status": "Cancelled"
}
]
}
And I was trying to achieve to rename the "Info" into "Description" without losing its value and array position. I'm not very familiar with array_replace , that seems my code is not working. Please share some codes, it will be much appreciated.
Here my PHP code I tried
<?PHP
$jsn = file_get_contents('./test.json');
$arr = json_decode($jsn, true);
$newArray= [];
foreach($arr['data'] as $row){
$row['Description'] = $row['Info'];
array_push($newArray, $row);
}
//print_r($newArray);
array_replace($arr['data'],$newArray);
echo json_encode($arr, JSON_PRETTY_PRINT);
Thank you so much for your attention and advance help. It will really gonna save me some time. Noob here and I'm still learning things about PHP and JSON

Laravel Query to select list entry in JSON field

I'm storing dynamic data in a MySQL JSON field using Laravel v6.11.0, nova v2.9.3 and nova-flexible-content v0.1.13. The data stored looks similar to this:
[
{
"layout": "source",
"key": "5ce8e0a877487fe5",
"attributes": {
"value": "342",
"unit": "USD",
"language": "en",
"url": "http:\\/\\/google.com",
"authority": "google.com",
"entry_date": "2020-01-21",
"date": "2019-12-21"
}
},
{
"layout": "source",
"key": "a82393ce016e8c14",
"attributes": {
"value": "444",
"unit": "USD",
"language": "en",
"entry_date": "2020-01-21",
"url": "https:\\/\\/google.com",
"authority": "TEST",
"date": "2020-01-20"
}
}
]
I was wondering if it's possible to build a Laravel Query to select the second entry based on the authority entry? Criteria are:
url should contain google.com AND
authority shouldn't be google.com
I've found https://laravel.com/docs/5.8/queries#json-where-clauses, but am struggling to put the right query together. Maybe someone could give me some pointers on how to do it? Thank you
You may refer to this discussion on Laracast
$data = App\YourModel::whereRaw('JSON_CONTAINS(body->"$[*].attributes.url", "\"https://google.com\"")')
->orWhereRaw('JSON_CONTAINS(body->"$[*].id", "\"http://google.com\"")')
->whereRaw('not JSON_CONTAINS(body->"$[*].attributes.authority", "\"google.com\"")')
->get();
foreach ($data as $key => $row) {
$bodyArr = json_decode($row->body);
foreach ($bodyArr as $item) {
if ((preg_match("/(http:\/\/www\.|https?:\/\/google.com)/i",$item->attributes->url)) && (strpos($item->attributes->authority, 'google.com') === false)) {
dump($item);
// YOUR CODE GOES HERE
}
}
}

JSON Post PHP (TypeForm)

I have never used JSON before so apologies if this is a simple request.
I have a webhook setup that sends me a JSON Post (Example Below) - I want to extract the two answers from this "text":"250252" & {"label":"CE"}
{
"event_id": "1",
"event_type": "form_response",
"form_response": {
"form_id": "VpWTMQ",
"token": "1",
"submitted_at": "2018-05-22T14:11:56Z",
"definition": {
"id": "VpWTMQ",
"title": "SS - Skill Change",
"fields": [
{
"id": "kUbaN0JdLDz8",
"title": "Please enter your ID",
"type": "short_text",
"ref": "9ac66945-899b-448d-859f-70562310ee5d",
"allow_multiple_selections": false,
"allow_other_choice": false
},
{
"id": "JQD4ksDpjlln",
"title": "Please select the skill required",
"type": "multiple_choice",
"ref": "a24e6b58-f388-4ea9-9853-75f69e5ca337",
"allow_multiple_selections": false,
"allow_other_choice": false
}
]
},
"answers": [
{
"type": "text",
"text": "250252",
"field": {
"id": "kUbaN0JdLDz8",
"type": "short_text"
}
},
{
"type": "choice",
"choice": {
"label": "CE"
},
"field": {
"id": "JQD4ksDpjlln",
"type": "multiple_choice"
}
}
]
}
}
I have this currently in my PHP file:
$data = json_decode(file_get_contents('php://input'));
$ID = $data->{"text"};
$Skill = $data->{"label"};
This does not work and all I get is null - Any help would really be appreciated, Thank You.
You need to look at the JSON object you're receiving to know the structure of the object you're receiving after using json_decode, what you're trying to get is in $data->form_response->answers, So you can have a variable for easier access:
$answers = $data->form_response->answers;
remember $answers is an array
So to achieve what you're trying to get, you can do:
$data = json_decode(file_get_contents('php://input'));
$answers = $data->form_response->answers;
$ID = $answers[0]->text;
$Skill = $answers[1]->choice->label;

Facebook - Get & Display me/og.likes in Video application

Have built an video app that publish user actions towards Facebook.
In this app i have implemented an "Favorite" function that i have hooked up towards a basic open graph action "og.like"
I want to be able to display video's that user liked and apply my own styling to that.
Basically i want to display "Title" "Url" & "Image"
So i use the PHP-SDK towards authored user with active access token and execute
$response = $facebook->api(
'me/og.likes',
'GET'
);
// handle the response
How do i now sort out my correct fields and display them ?
Am not hardcore at either php or javascript but will be able to sort this out if i just can get a little push in the right direction. Like just showing the raw data
Update
Finally a little progress, adding
print_r ($response);
Will write out the raw data, Now i know that am on the right way.
Array returned
{
"data": [
{
"id": "123",
"from": {
"name": "Mathias",
"id": "APP_ID"
},
"start_time": "X",
"end_time": "X",
"publish_time": "X",
"application": {
"name": "APP_Name",
"namespace": "",
"id": "321"
},
"data": {
"object": {
"id": "139",
"url": "Url to like",
"type": "video.tv_show",
"title": "title"
}
},
"type": "og.likes",
"no_feed_story": false,
"likes": {
"count": 0,
"can_like": true,
"user_likes": false
},
"comments": {
"count": 0,
"can_comment": true,
"comment_order": "chronological"
}
},
And then the next..
From every app "like" i would like to display Url ,Title & Image
From what i understand so far my main problem is that this is nested arrays, Did try with single level arrays and there i did manage to display correct data just by
echo $response[name];
So how do i digg in and loop this around, All tips are welcome,
{
"id": "139",
"url": "url",
"type": "video.tv_show",
"title": "titke",
"image": [
{
"url": "image_URL",
"secure_url": "image_URL",
"type": "image/jpg",
"width": 1024,
"height": 576
}
Here's an example:
<?php foreach ( $response['data'] as $data ): ?>
<?php $Object = $data['data']['object']; ?>
<?php echo $Object['title']; ?><br />
<?php endforeach; ?>

imploding array_keys from Facebook JSON data

Need some help with the sample code provided the facebook. I can't get it to return a series of IDs that I need to run a sql query against.
$friends = '{
"data": [
{
"name": "Paul",
"id": "12000"
},
{
"name": "Bonnie",
"id": "120310"
},
{
"name": "Melissa",
"id": "120944"
},
{
"name": "Simon",
"id": "125930"
},
{
"name": "Anthony",
"id": "120605"
},
{
"name": "David",
"id": "120733"
}
]
}';
$obj = json_decode($friends);
print $obj->{'data'}[0]->{'name'};
I can return the "Paul"
what I want is to return all the id's using implode(array_keys($obj),",")
I am only getting data to return.
What I'd like to do is retrieve all the IDs separated by a comma.
Thanks!
Try implode-ing on the data key with array_map:
function get_id($o) {
return $o->id;
}
implode(array_map('get_id', $obj->data),",")

Categories