How to echo only one post from a jsonfile - php

I have made a Module which displays the latest images from a instagram profile, and it works perfectly in Joomla 3.4.8 with a small popup gallery
I would like to add the profile image - profile_picture, but of course it should only appear once.
I have tried various php echo - but no luck
Can anyone help?
The PHP
<?php
// Supply a user id and an access token
$userid = $params->get('klintweb_insta_id');
$accessToken = $params->get('klintweb_insta_access_token');
$count = $params->get('klintweb_insta_count');
// Gets post and image
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?count={$count}&access_token={$accessToken}");
$result = json_decode($result);
?>
The foreach
<?php foreach ($result->data as $post): ?>
{emailcloak=off}
<!-- Renders images. #Options (thumbnail,low_resoulution, high_resolution) -->
<span class="KlintWebInstaSpan">
<a data-mediabox-group="insta" type="image/jpeg" class="jcepopup noicon" data-mediabox-caption="<?= rtrim(strip_tags(substr ($post->caption->text,0,140))).'...'; ?>" data-mediabox-title="rasmusjorgensen128" href="<?= $post->images->standard_resolution->url ?>">
<img src="<?= $post->images->thumbnail->url ?>" alt="Billede fra instagram" />
<span class="overlay"></span>
</a>
</span>
<?php endforeach ?>
The jsonfile
{
"data": [{
"comments": {
"count": 0
},
"caption": {
"created_time": "1296710352",
"text": "Inside le truc #foodtruck",
"from": {
"username": "kevin",
"full_name": "Kevin Systrom",
"type": "user",
"id": "3"
},
"id": "26621408"
},
"likes": {
"count": 15
},
"link": "http://instagr.am/p/BWrVZ/",
"user": {
"username": "kevin",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_3_75sq_1295574122.jpg",
"id": "3"
},
"created_time": "1296710327",
"images": {
"low_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/6ea7baea55774c5e81e7e3e1f6e791a7_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/6ea7baea55774c5e81e7e3e1f6e791a7_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/6ea7baea55774c5e81e7e3e1f6e791a7_7.jpg",
"width": 612,
"height": 612
}
},
"type": "image",
"users_in_photo": [],
"filter": "Earlybird",
"tags": ["foodtruck"],
"id": "22721881",
"location": {
"latitude": 37.778720183610183,
"longitude": -122.3962783813477,
"id": "520640",
"street_address": "",
"name": "Le Truc"
}
},
{
"videos": {
"low_resolution": {
"url": "http://distilleryvesper9-13.ak.instagram.com/090d06dad9cd11e2aa0912313817975d_102.mp4",
"width": 480,
"height": 480
},
"standard_resolution": {
"url": "http://distilleryvesper9-13.ak.instagram.com/090d06dad9cd11e2aa0912313817975d_101.mp4",
"width": 640,
"height": 640
},
"comments": {
"count": 2
},
"caption": null,
"likes": {
"count": 1
},
"link": "http://instagr.am/p/D/",
"created_time": "1279340983",
"images": {
"low_resolution": {
"url": "http://distilleryimage2.ak.instagram.com/11f75f1cd9cc11e2a0fd22000aa8039a_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage2.ak.instagram.com/11f75f1cd9cc11e2a0fd22000aa8039a_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage2.ak.instagram.com/11f75f1cd9cc11e2a0fd22000aa8039a_7.jpg",
"width": 612,
"height": 612
}
},
"type": "video",
"users_in_photo": null,
"filter": "Vesper",
"tags": [],
"id": "363839373298",
"user": {
"username": "kevin",
"full_name": "Kevin S",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_3_75sq_1295574122.jpg",
"id": "3"
},
"location": null
},
]
}
Thanks to Adam Taylor
You pointed how simple it can be done
Also thanks to Danoweb for helping

Am I right in understanding you're looping through a list of photos and you want to also access the profile picture and print it once?
Do you need to loop through all the photos? If not, you could add a break after you've printed the photo, to exit the loop.
If you need to loop through the photos as well, why not access the first element in the JSON, take the profile picture from there, and then loop through the rest of the photos?
Edit:
In regards to your solution, it might be easier to just access the first photo directly, print the associated user thumbnail, and then continue with your loop and printing of all the photos. Something like:
<div class="user">
<?php $post = $result->data[0]; ?>
<img src="<?= $post->user->profile_picture ?>" alt="<?= $post->user->username ?>" />
<span class="username"><?= $post->user->username ?></span>
</div>
<!-- do the rest of your looping/displaying photos -->
In your solution you are slicing the array to one element and then looping over the array when all you really want to do is access the first element.

From what I understand it looks like the profile picture is provided twice within the JSON response. What I would use is a variable to track whether or not I have already shown the profile picture, and if so, don't show the second one. For Example:
<?php
$shown_profile = false;
foreach ($result->data as $post)
{
//WE HAVE NOT SHOWN PROFILE PIC, SHOW IT AND SET FLAG.
if($shown_profile == false and (image is profile pic) )
{
$shown_profile = true;
}
//WE HAVE ALREADY SHOWN PROFILE PIC AND THIS IMAGE IS A DUPLICATE
if($shown_profile == true and (image is profile pic) )
{
//JUMP TO THE NEXT LOOP INTERATION
continue;
}
//[THE REST OF YOUR FOREACH CODE]
}
?>
You can find more info about the "continue" statement here:
http://php.net/manual/en/control-structures.continue.php
Hope this helps!

Related

get array content from json (telegram api) in php

I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.

How to get values from json encode in php?

I have a json like this
{
"data": [
{
"description": "~~ funny ~~
for more pictures , visit www.1mpics.com
Para mais imagens , visite www.1mpics.com",
"media": {
"image": {
"height": 429,
"src": "https://scontent.xx.fbcdn.net/hphotos-xfa1/v/t1.0-9/281318_366934083403548_1944634610_n.jpg?oh=6d6321885ff621cc79c404b0aa559c21&oe=5617A0FB",
"width": 550
}
},
"target": {
"id": "366934083403548",
"url": "https://www.facebook.com/1mpics/photos/a.348356355261321.82963.237513286345629/366934083403548/?type=1"
},
"title": "Timeline Photos",
"type": "photo",
"url": "https://www.facebook.com/1mpics/photos/a.348356355261321.82963.237513286345629/366934083403548/?type=1"
}
]
}
now I want "src" from the json. Therefore I create code like this where I pass the json array through post method
$json = $_POST["a"];
$json = json_decode($json, true);
echo $json['scr'];
but it is not working.
try
echo $json['data'][0]['media']['image']['src']

Trouble retrieving video info from JSON data using PHP for and foreach loops - YouTube API 3

Basically I want to list the last uploads of a YouTube channel, but I had trouble using the for loop or I am missing foreach use as well.
I have tried the following:
function last_uploads() {
for($i = 0; $i < 20; ){
error_reporting(E_ALL);
$url = 'https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCBR8-60-B28hp2BmDPdntcQ&maxResults=3&key={key}&type=video';
$json = file_get_contents($url);
$json_data = json_decode($json, false);
$id = $json_data->items[0]->id->videoId;
echo '<iframe id="ytplayer" type="text/html" width="auto" height="auto"
src="http://www.youtube.com/embed/' . $id . '?rel=0&showinfo=1"
frameborder="0" allowfullscreen></iframe><br class="clear" />';
}
$i++;
break;
}
The output of the feed url ( $url ) is the following:
{
"kind": "youtube#searchListResponse",
"etag": "\"IHLB7Mi__JPvvG2zLQWAg8l36UU/sa0AWnsYjVk9MPM3sjMlLcrfFxU\"",
"nextPageToken": "CAMQAA",
"pageInfo": {
"totalResults": 219,
"resultsPerPage": 3
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"IHLB7Mi__JPvvG2zLQWAg8l36UU/2QHwn2uxHHlB9OQ9ViQw0LdnQwI\"",
"id": {
"kind": "youtube#video",
"videoId": "AbqT_ubkT0Y"
},
"snippet": {
"publishedAt": "2015-03-03T17:44:56.000Z",
"channelId": "UCBR8-60-B28hp2BmDPdntcQ",
"title": "#DearMe - What Advice Would You Give Your Younger Self?",
"description": "Share your advice by making your own #DearMe GIF at http://youtubedearme.com ** In celebration of International Women's Day, take part in YouTube's global ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/AbqT_ubkT0Y/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/AbqT_ubkT0Y/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/AbqT_ubkT0Y/hqdefault.jpg"
}
},
"channelTitle": "YouTube",
"liveBroadcastContent": "none"
}
},
{
"kind": "youtube#searchResult",
"etag": "\"IHLB7Mi__JPvvG2zLQWAg8l36UU/PoM38fElRhJodbFBOt_g1xgJ2RE\"",
"id": {
"kind": "youtube#video",
"videoId": "OUmMAAPX6E8"
},
"snippet": {
"publishedAt": "2015-02-23T14:35:35.000Z",
"channelId": "UCBR8-60-B28hp2BmDPdntcQ",
"title": "Introducing the YouTube Kids app",
"description": "Download YouTube Kids for free on your Android or iOS device. Android: http://goo.gl/SsDTHh iOS: http://goo.gl/P0cikI The YouTube Kids app is designed for ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/OUmMAAPX6E8/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/OUmMAAPX6E8/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/OUmMAAPX6E8/hqdefault.jpg"
}
},
"channelTitle": "YouTube",
"liveBroadcastContent": "none"
}
},
{
"kind": "youtube#searchResult",
"etag": "\"IHLB7Mi__JPvvG2zLQWAg8l36UU/-017SY9hNMURE5Slk5j5CU087wE\"",
"id": {
"kind": "youtube#video",
"videoId": "SDdXVOD4llU"
},
"snippet": {
"publishedAt": "2015-01-24T02:59:11.000Z",
"channelId": "UCBR8-60-B28hp2BmDPdntcQ",
"title": "Highlights From the YouTube Interview with President Obama",
"description": "On Jan 22, 2015, President Obama sat down for his first interview after the State of the Union with popular YouTube creators, Bethany Mota, Hank Green and ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/SDdXVOD4llU/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/SDdXVOD4llU/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/SDdXVOD4llU/hqdefault.jpg"
}
},
"channelTitle": "YouTube",
"liveBroadcastContent": "none"
}
}
]
}
The issue is that last_uploads() returns the last 1 video and keeps repeating it until 120 seconds exceeded error appears.
Any thoughts?
Regards,
Thank you!
It's just messed up.
Your for loop will execute indefinitely until timeout because the $i++ is AFTER the for loop. (Truth is, the for loop isn't even needed because you're fetching the latest 3 videos from the channel - no need to do that 20 times).
Your code only fetches the id of the first video that is returned. This is where a for loop should be to loop through the results.
foreach ( $json_data->items as $item ) {
$id = $item->id->videoId;
# print your stuff
}
Thanks to #johnh10 [ answer ], deleting for loop got it working:
function last_uploads() {
$url = 'https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=UCBR8-60-B28hp2BmDPdntcQ&maxResults=3&key={key}&type=video';
$json = file_get_contents($url);
$json_data = json_decode($json, false);
foreach ( $json_data->items as $item ) {
$id = $item->id->videoId;
echo '<iframe id="ytplayer" type="text/html" width="auto" height="auto"
src="http://www.youtube.com/embed/' . $id . '?rel=0&showinfo=1"
frameborder="0" allowfullscreen></iframe><br class="clear" />';
}
}
Thanks John :)

Reading a large JSON from Facebook

How can I read several values with the same name from a JSON from Facebook, when I use this code:
$urlamandar = 'https://graph.facebook.com/'.$user."?access_token=".$access_token;
$content = file_get_contents($urlamandar);
$obj = json_decode($content, true);
$obj = json_decode($content);
It displays this:
{
"id": "XXXXXXXX",
"name": "Ricardo Capistran",
"first_name": "Ricardo",
"last_name": "Capistran",
"gender": "male",
"locale": "es_MX",
"username": "richycapy"
}
And since because there is only one ID, one NAME, one USERNAME, etc, Its quite simple place them in vars like so:
$fbuserid = $obj->{'id'};
$fbname = $obj->{'name'};
$fbusername = $obj->{'username'};
$fbemail = $obj->{'email'};
$fbbirthday = $obj->{'birthday'};
But when it comes to larger files like this code:
$urlamandar = 'https://graph.facebook.com/'.$user.'/albums?access_token='.$access_token;
Its displays a way bigger array like so:
{
"data": [
{
"id": "10150732237818223",
"from": {
"name": "Ricardo Capistran",
"id": "XXXXXXX"
},
"name": "EnterateNorte.com Photos",
"link": "https://www.facebook.com/album.php?fbid=10150732237818223&id=743158222&aid=457026",
"privacy": "custom",
"count": 31,
"type": "app",
"created_time": "2012-03-11T02:44:42+0000",
"updated_time": "2014-01-07T03:13:24+0000",
"can_upload": false
},
{
"id": "440168313222",
"from": {
"name": "Ricardo Capistran",
"id": "743158222"
},
"name": "Timeline Photos",
"link": "https://www.facebook.com/album.php?fbid=440168313222&id=743158222&aid=220377",
"cover_photo": "10151730849598223",
"privacy": "everyone",
"count": 175,
"type": "wall",
"created_time": "2010-06-30T22:38:45+0000",
"updated_time": "2014-01-01T02:09:11+0000",
"can_upload": false
},
{
"id": "10150797320378223",
"from": {
"name": "Ricardo Capistran",
"id": "743158222"
},
"name": "Instagram Photos",
"link": "https://www.facebook.com/album.php?fbid=10150797320378223&id=743158222&aid=466555",
"cover_photo": "10151695050098223",
"privacy": "friends",
"count": 37,
"type": "app",
"created_time": "2012-04-09T23:50:08+0000",
"updated_time": "2013-12-29T08:29:15+0000",
"can_upload": false
}
],
"paging": {
"cursors": {
"after": "NDM1NjY5NjI4MjIy",
"before": "MTAxNTA3MzIyMzc4MTgyMjM="
},
"next": "https://graph.facebook.com/*my_id*/albums?access_token=*access_token*&limit=25&after=NDM1NjY5NjI4MjIy"
}
}
And I would need the “name” and “id” off all the albums, so then I can repeat this same procedure with the containing pictures
Obviously it has way more albums, I just cut it after 3 just to explain my self…
Is there a way to place them in vars? With a php “for each” some how
Thanks!
You can do something like
$obj = json_decode($content, true);
$array_album = array();
foreach($obj['data'] as $key=>$val){
$array_album[] = array("id"=>$val["id"],"name"=>$val["name"]);
echo "ID : ".$val["id"]. " NAME : ".$val["name"] ;
echo "<br />";
}
print_r($array_album); // This will have all the id and names
If you dont want to store in array then the names and id will appear in the above loop and you can do whatever you want with those values. Or use the array $array_album and loop through if you want to use it later.

How to get the profile picture of user posts from Facebook API search results?

$search = $facebook->api('/search?q=watermelon&type=post');
returns something like this:
{
"data": [
{
"id": "1194579494_10201162886052970",
"from": {
"name": "Dawn Rittman Stoltz",
"id": "1194579494"
},
"message": "Our first watermelon and pumpkin from the farm!!! We rock at this garden thing",
"picture": "https://fbcdn-photos-f-a.akamaihd.net/hphotos-ak-ash3/563531_10201162883172898_1559330219_t.jpg",
"link": "https://www.facebook.com/photo.php?fbid=10201162883172898&set=pcb.10201162886052970&type=1&relevant_count=2",
"icon": "https://static.xx.fbcdn.net/rsrc.php/v2/yx/r/og8V99JVf8G.gif",
"privacy": {
"value": ""
},
"type": "photo",
"object_id": "10201162883172898",
"application": {
"name": "Facebook for iPhone",
"namespace": "fbiphone",
"id": "6628568379"
}
],
"paging": {
"previous": "https://graph.facebook.com/search?type=post&q=watermelon&limit=25&since=1379461168",
"next": "https://graph.facebook.com/search?type=post&q=watermelon&limit=25&until=1379460365"
}
}
Is there a more efficient way than getting the id of the facebook user and making a bunch of requests to get their profile picture from the api like this?
$data = $search['data'];
$picture_urls = array();
foreach ($data as $status) {
$from = $status['from'];
$id = $from['id'];
$picture = $facebook->api('/' . $id . '/picture?type=square&redirect=false');
$picture_data = $picture['data'];
$picture_url = $picture_data['url'];
array_push($picture_urls, $picture_url);
}
You can get the picture field directly in your first call. Try this-
/search?q=watermelon&type=post&fields=from.picture

Categories