Pull JSON API results from URL and display in PHP - php

I've been trying to do this for a couple of days through trial and error etc, but getting absolutely nowhere. PHP isn't my strong point, but I'm generally comfortable with it that I can learn as I go when I need to do specific things.
What I'm trying to do, is take the API from one platform that is used, and input it into another platform that is used. I can get the data from the API easily enough via a URL, and it runs fine on a different server so I'm pretty sure everything is fine on that side of things.
The issue is, that when I do manage to get it from a URL, it comes out looking quite messy. Nothing I've tried so far will display it as a nice tidy block. Furthermore, I'd like to be able to pull specific data from the result and display just that. The data comes out as follows when visited via the URL (have changed values for privacy etc, but the integrity should remain):
{"Data":[{"DeviceID":"1","DeviceName":"Phone 1","Platform":"Phone OS","Edition":"Deluxe","State":"0","Time":"2016-03-16T13:47:44+01:00"}]}
Essentially, what I'm trying to do is:
Display the data in a block list, as opposed to long lines
Allow selection of a specific device through "Device Name", and then display the information relevant to that device
I've tried the following scripts so far:
1:
<?php
$json = file_get_contents('URLHERE');
$obj = json_decode($json);
echo $obj->DeviceID;
?>
2:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'URLHERE');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $result->DeviceName;
?>
3:
<?php
$url = 'URLHERE';
$obj = json_decode(file_get_contents($url), true);
echo $obj['DeviceID'];
?>
4:
<?php
$url = "URLHERE";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "Device: ". $json_data["DeviceID"];
?>
5:
<?php
$json = file_get_contents('URLHERE');
$encodeJ = utf8_encode($json);
$obj = json_decode($encodeJ);
var_dump($obj-> DeviceID);
?>
The fourth one is the closest I've managed to get to it displaying data using these methods, but rather than any information I just get "Device: NULL"
Any help would be appreciated. Starting to pull my hair out here!
UPDATE:
Have managed to make some progress with the following:
<?php
$data = file_get_contents('URLHERE');
$response = json_decode($data, true);
echo 'Device: ' . $response['Data']['0']['DeviceName'];
echo 'Device: ' . $response['Data']['1']['DeviceName'];
?>
This is displaying the device names from the array for value 0 and 1. So now I need to figure out how to iterate through the array and display each one in sequence, as opposed to hard coding each one.

Your DeviceID is in Data & it's an array so you can't access directly. When you
$data = json_decode('{"Data":[{"DeviceID":"1","DeviceName":"Phone 1","Platform":"Phone OS","Edition":"Deluxe","State":"0","Time":"2016-03-16T13:47:44+01:00"}]}', true);//I am using array so second parameter is true to easily demonstrate
Your structure is
[
"Data" => [
[
"DeviceID" => "1",
"DeviceName" => "Phone 1",
"Platform" => "Phone OS",
"Edition" => "Deluxe",
"State" => "0",
"Time" => "2016-03-16T13:47:44+01:00",
],
],
]
So to get only first DeviceID if you want then
$deviceID = isset($data['Data'][0]['DeviceID']) ? $data['Data'][0]['DeviceID'] : null;
or if you want all the DeviceIDs then
$deviceIds = [];
if (isset($data['Data']) && is_array($data['Data']))
{
foreach ($data['Data'] as $row)
{
if (isset($row['DeviceID']))
{
$deviceIds[] = $row['DeviceID'];
}
}
}
or you can use array_column if your php version is >= 5.5.0 or php 7
$deviceIds = [];
if (isset($data['Data']) && is_array($data['Data']))
{
$deviceIds = array_column($data['Data'], 'DeviceID');
}

To get the data, use:
$json = file_get_contents( $url );
Then get it into an array, as:
$arr = json_decode( $json, TRUE );
To "Display the data in a block list, as opposed to long lines", use:
foreach ( $arr AS $element ) {
foreach ( $element AS $e ) {
echo $e['DeviceName'] . '<br>';
}
}
To "Allow selection of a specific device through "Device Name", and then display the information relevant to that device", use:
$deviceName = "Phone 1"; // depending upon your use case, you'll need to decide how you want to set this variable; it's hard coded here for the sake of example
foreach ( $arr AS $element ) {
foreach ( $element AS $e ) {
if ( $e['DeviceName'] = $deviceName ) {
echo '<pre>';
print_r( $e );
echo '</pre>';
}
}
}
While it's not entirely clear what you mean by "Allow selection of a specific device through "Device Name"", I'm inclined to believe you're looking for a way to let a user select a device from the list of device names. That's not a task you can accomplish with PHP alone. You'll need to build something for the front end in HTML or Javascript that interacts with your PHP on the back end.

Related

Youtube get video title from id

I understand this may have been answered somewhere, but after looking and looking through numerous questions/answers and other websites, I'm unable to find a suitable answer.
I'm trying to create a page, which will show some video from Youtube. It will show the image, and title. I've managed to do both of these, although i'm having problems with the title. With the code i'm using, it is awfully slow at loading. I assume because of it loading the actual website just to get the title.
This is what i'm using to get the titles currently.
function get_youtube_id($url){
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
return $my_array_of_vars['v'];
}
function get_youtube_title($video_id){
$url = "http://www.youtube.com/watch?v=".$video_id;
$page = file_get_contents($url);
$doc = new DOMDocument();
$doc->loadHTML($page);
$title_div = $doc->getElementById('eow-title');
$title = $title_div->nodeValue;
return $title;
}
So, how would the best way to get a youtube title by the id. The code I have does work, but it also makes the page load very very slow.
Thanks
Here is a simple way to do it using PHP and no library. YouTube already allows you to retrieve video detail information in the JSON format, so all you need is a simple function like this:
function get_youtube_title($ref) {
$json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
$details = json_decode($json, true); //parse the JSON into an array
return $details['title']; //return the video title
}
The function parameter being the video ID. You could also add a second parameter asking for a specific detail and change the function name so you could retrieve any data from the JSON that you would like.
EDIT:
If you would like to retrieve any piece of information from the returned video details you could use this function:
function get_youtube_details($ref, $detail) {
if (!isset($GLOBALS['youtube_details'][$ref])) {
$json = file_get_contents('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=' . $ref . '&format=json'); //get JSON video details
$GLOBALS['youtube_details'][$ref] = json_decode($json, true); //parse the JSON into an array
}
return $GLOBALS['youtube_details'][$ref][$detail]; //return the requested video detail
}
If you request different details about the same video, the returned JSON data is stored in the $GLOBALS array to prevent necessary calls to file_get_contents.
Also, allow_url_fopen will have to be on in your php.ini for file_get_contents to work, which may be a problem on shared hosts.
You can use Open Graph
Checkout This Link
<?php
require_once('OpenGraph.php');
function get_youtube_title($video_id){
$url = "http://www.youtube.com/watch?v=".$video_id;
$graph = OpenGraph::fetch($url);
// You can get title from array
return $graph->title;
}
It's been 5 years, but my script bellow could be useful.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.youtube.com/watch?v=YOUTUBEID");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$document = htmlspecialchars($output);
curl_close($ch);
$line = explode("\n", $document);
$judul = "";
foreach($line as $strline){
preg_match('/\<title\>(.*?)\<\/title\>/s', $strline, $hasil);
if (!isset($hasil[0]) || $hasil[0] == "") continue;
$title = str_replace(array("<title>", "</title>"), "", $hasil[0]);
}
echo $title;

Getting a specific value from an array

I'm trying to get a specific column from an array for each record returned.
The array is called fields and one of the arrays in the array is locations. I'm looking for a specific column in the array called name.
Here's what I have:
foreach ($new_results as $result):?>
$locations = array_map($result->locations->location,function($obj) { return $obj->location; });
echo implode(",",$locations);
endforeach;
I'm connecting to a web service to pull this data. The above is the code that the company gave me, but they haven't tested it as far as I know. It doesn't work for me.
Here's the call to the API
$results = $connection->call('groups/getAll', $params=array("suspended" => "no","fields" =>"locations"));
$new_results = $results->groups->group;
Here's an example from the API.
{
"id": "xxxx",
"fields": {
"locations": [
"North",
"Central"
]
}
}
Any thoughts on what I'm doing wrong? I'm still very new to PHP so I may be missing something very obvious.
How to get json using curl:
How to get JSON data from Rest API by PHP Curl?
Now with that in mind you can dive a little deeper into the object manipulation in terms of the response here: Accessing JSON object elements in PHP.
//""" code from the first link
$service_url = "http://127.0.0.1:8000/api/thesis/?format=json";
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
//execute the session
$curl_response = curl_exec($curl);
//finish off the session
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);
//""" code from the first link
&
//""" code from the second link
/*Variable passed in from the ExtJS interface as JSON object*/
$json = $_POST["newUserInfo"];
//$json = '{"USER":{"ID":"","FULL_USER_NAME":"Some Guy","ENTERPRISE_USER_NAME":"guyso01","USER_EMAIL":"Some.Guy#Email.com","USER_PHONE":"123-456-7890"},"PERMISSIONS":{"ID":"","USER_ID":"","IS_ADMIN":"true"},"SETTINGS":{"ID":"","USERS_ID":"","BACKGROUND":"default"}}';
//Test to view the decoded output
//var_dump(json_decode($json));
//Decode the $json variable
$jsonDecoded = json_decode($json,true);
//Create arrays for each table from the $jsonDecoded object
$user_info = array($jsonDecoded['USER']);
$permissions_info = array($jsonDecoded['PERMISSIONS']);
$settings_info = array($jsonDecoded['SETTINGS']);
// """ code from the first link

Issue displaying json feed items using PHP

I am very new to json in combination with php and wonder why the following code is not working. My mission is displaying the title items one by one.
<?php
$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48");
$parsed_json = json_decode($json_string, true);
$parsed_json = $parsed_json['gigs'];
foreach($parsed_json as $key => $value)
{
echo $value['title'] . '<br>';
}
?>
The next issue will by, how would I be able to save the image item called cloud_img_med to my server into /grabbed
Your help would be greatly appreciated.
To answer your question about why this code isn't working:
I tried to set it up myself, and found out that the output fetched by file_get_contents is compressed. You can see that by reading the output in a simple var_dump:
var_dump($json_string);
To fix this, you'll need to use a custom context with no compression:
$context = stream_context_create(
array(
'http' => array(
'method' => "GET",
'header' => "Accept-Encoding: gzip;q=0, compress;q=0\r\n",
)
));
Then pass it as the third parameter:
$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48", false, $context);
I should do this JSON string readable
The code seems to work fine - I tried it on my local machine.
Running this
<?php
$str = <<<EOT
// JSON here...
EOT;
$parsed_json = json_decode($str, true);
$parsed_json = $parsed_json['gigs'];
foreach($parsed_json as $key => $value)
{
echo $value['title'] . '<br>';
}
?>
Gives me this output
replace the MGM lion with your pet or whoever<br>design creative Animal And Pet Company logo<br>`
Which is sort of what you want? If you're having trouble, maybe file_get_contents isn't allowed on your server and you can't get the JSON. Try hardcoding it into the $str variable like I did, and see if you get what you want.
With regards to saving the image, you can check this answer here: https://stackoverflow.com/a/724449/4396258
I think the problem might be the data you're getting from Fiverr's JSON API. At least in my test, I found it was using gzip encoding to compress the data you're requesting. So you have to uncompress it.
$json_string = file_get_contents("https://www.fiverr.com/gigs/gigs_as_json?host=search&type=single_query&query_string=pet&search_filter=rating&category_id=3&sub_category_id=49&limit=48");
$content = json_decode(gzinflate( substr($json_string,10,-8) ));
$gigs = $content->gigs;
foreach($gigs as $key => $value)
{
echo $value->title . '<br>';
}

JSON to PHP Output

I usually manage to figure stuff out by myself, but on this occasion I've had to register an account and ask for help before I jump out the window.
I'm trying to output some basic JSON data to php, all I need to do is echo it out, the rest I'll figure out.
The API gives this guide:
{
"success" : true,
"message" : "",
"result" : {
"Bid" : 2.05670368,
"Ask" : 3.35579531,
"Last" : 3.35579531
}
}
An example of the URL I'll be using: https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC
All I want to output is the 'Last' data, I don't care about the rest, keeping the decimal in the right place is also important.
I've tried all sorts, I can't get it to output it properly :(. I've ran a var_dump which spits out:
array(3) { ["success"]=> bool(true) ["message"]=> string(0) "" ["result"]=> array(3) { ["Bid"]=> float(0.00011505) ["Ask"]=> float(0.000116) ["Last"]=> float(0.00011505) } }
If someone could just tell me the few lines of code to put the 'Last' number into a variable called $lastBid I will love you long time!
Thanks guys!
use json_decode - php method to decode json
http://php.net/manual/en/function.json-decode.php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
Here you have an example,
$contents = file_get_contents("https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC");
$json = json_decode($contents);
$lastBid = $json->result->Last;
$lastBid would then be set to 0.01189802
You need to json_decode() the result.
that kind of data is called json. php permits you to convert that json (which is a string) to a php array.
to get it, you need to convert it and then access to the value you'd like using array rules.
// save in a variable the data you're going to process
$json = '{
"success" : true,
"message" : "",
"result" : {
"Bid" : 2.05670368,
"Ask" : 3.35579531,
"Last" : 3.35579531
}
}';
// json_decode is a function that allows you to obtain an array
// (the second parameter set to true indicates that the array'll be an associative one)
$data = json_decode($json, TRUE);
/*
every php array has an internal pointer which points to a position in the array.
the end pointer, if not moved, points to the last position. to access to the value
you want, first get the last value (an array called "result"),
then access to the last value of that array (called "last").
the property you'll get is the float value you requested!
*/
var_dump(
end(
end($data)
)
);
and here, there is the output:
float(3.35579531)
Access it by:
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = file_get_contents($url);
$data = json_decode($data);
$last = $data->result->Last;
If you like using arrays instead of object orrientation style, json_decode has an extra boolean param, that converts it too an array if you feel more comfortable using that.
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = file_get_contents($url);
$data = json_decode($data,true);
$last = $data['result']['Last'];
Side note; For accessing API's I would rather advice you to use curl instead of file_get_contents. It gives you better control, for instance with timeouts. But you have many more options. You can use this function;
function curl($URL,&$errmsg){
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
$contents = curl_exec($c);
if (curl_errno($c)){
$errmsg = 'Failed loading content.';
curl_close($c);
return;
}
else{
curl_close($c);
return($contents);
}
}
And your code then would be:
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = curl($url, $errmsg);
$data = json_decode($data,true);
$last = $data['result']['Last'];

how to get pictures url from instagram API Json result

I´m currently trying to get all the URLs for my pictures from my instagram feed and print them out in a simple HTML gallery.
I have managed with "some help" to authenticate and get an accesstoken which allows me to get a JSON result containing all my pictures, but I´m totally new to how to fetch all the pictures with the help of JSON.
The code I've got so far looks like this:
<?php
session_start();
//require_once 'src/config.php';
$n_client_id = '87fdd319f8244a728a86f3692527fb15';
$n_client_secret = '040d431d4e0247a292612229446b5240';
$n_redurect_uri = 'http://ideweb2.hh.se/~lukpal12/Startsida.php';
//require_once 'src/Instagram.php';
date_default_timezone_set('UTC');
$url = "https://api.instagram.com/oauth/access_token";
$access_token_parameters = array(
'client_id' => $n_client_id,
'client_secret' => $n_client_secret,
'grant_type' => 'authorization_code',
'redirect_uri' => $n_redurect_uri,
'code' => $_GET["code"]
);
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_parameters);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$authObj = json_decode($result);
print_r($result);
$instagram = <<<END
Get pictars!
END;
echo $instagram;
echo $authObj->access_token;
?>
Since I'm completely new to JSON and how to work with it, I have no idea how the code should be written to do what I'm asking.
After some searching around and after a video or two explaining JSON I managed to get this code to do the Json_decode:
$json = file_get_contents("https://api.instagram.com/v1/users/2912979/media/recent/?access_token=2912979.87fdd31.0949d22f4a714349ae84643c5af165ef");
$data = json_decode($json);
echo $data->standard_resolution[0]->url;
But that does not work at all. I've got the link to the JSON containing all the data here:
https://api.instagram.com/v1/users/2912979/media/recent/?access_token=2912979.87fdd31.0949d22f4a714349ae84643c5af165ef
If someone would be kind enough to help me out.
First loop will give an array of images with all resolutions, while the second one an array with only standard_resolutions, use print_r to inspect the arrays.
$json = file_get_contents("https://api.instagram.com/v1/users/2912979/media/recent/?access_token=2912979.87fdd31.0949d22f4a714349ae84643c5af165ef");
$data = json_decode($json);
// to get the array with all resolutions
$images = array();
foreach( $data->data as $user_data ) {
$images[] = (array) $user_data->images;
}
// print_r( $images );
// to get the array with standard resolutions
$standard = array_map( function( $item ) {
return $item['standard_resolution']->url;
}, $images );
// print_r( $standard );
EDIT
To put these images to a gallery use foreach loop. See the PHP manual on how to use an array.
foreach( $standard as $url ) {
echo "<img src=\"$url\">";
}

Categories