Pull FIRST result from JSON decoded data in PHP - php

I have a script:
$json_url = "https://blockchain.info/ticker";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "$" . ($data->USD->last);
This works perfect!
Now I have a second version of this:
$json_url3 = "https://blockchain.info/da/unconfirmed-transactions?format=json";
$json3 = file_get_contents($json_url3);
$json3=str_replace('},
]',"}
]",$json3);
$data3 = json_decode($json3);
echo "Latest hash: " . ($data3->txs->hash) . "<br>";
Why does the send script not work? I have a $json2 running without any issues with another API call as well.

Variable txs is an array of objects.
Your last line should be written as:
echo "Latest hash: " . ($data3->txs[0]->hash) . "<br>";
It outputs:
Latest hash: fd37b1ddfbe08d485a62bb3aeb7c9088e7dd3a352ac9e9e8eb6f170a9b4210cd

This code worked :)
$json_url3 = "https://blockchain.info/da/unconfirmed-transactions?format=json";
$json3 = file_get_contents($json_url3);
$json3=str_replace('},
]',"}
]",$json3);
$data3 = json_decode($json3);
echo "Latest hash: " . ($data3->txs[0]->hash) . "<br>";
txs[0]
I assume the issue was that there is more than 1(one) element in the array

Related

Combine 2 place request to get postal code

I would like to combine two place-api calls in one to get further information about listings.
Example:
My first script request provides Name and Address from the API. However, the Placesearch API does not provide the postal code or other information I need.
My current script shows me this:
name;adress,lnt,lng,place_id
but I need more information for each listing, like the postal code, which not included here.
How can I include a 2nd API call for each place_id and display the postal code?
$apikey = 'KEY';
$url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.374,10.1495&rankby=distance&name=keyword&language=de&key=$apikey";
$json = file_get_contents($url);
$obj = json_decode($json, true);
for($i=0; $i<count($obj['results']); $i++) {
echo "" . $obj['results'][$i]['name'] . ";" . $obj['results'][$i]['vicinity'] . ";" . $obj['results'][$i]['geometry']['location']['lat'] . ";" . $obj['results'][$i]['geometry']['location']['lng'] . ";" . $obj['results'][$i]['place_id'] . DISPLaY POSTCODE "<BR>";
};
I know, I need to run this query for each place_id:
https://maps.googleapis.com/maps/api/place/details/json?placeid=$place_id=name,rating,formatted_phone_number&key=YOUR_API_KEY
But how can I combine it together with the first results? I need:
Name;Adress;Postcode;LAT;LNG;
Update:
1st request:
$apikey = 'KEY';
$url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.374,10.1495&rankby=distance&name=keyword&language=de&key=$apikey";
$json = file_get_contents($url);
$obj = json_decode($json, true);
for($i=0; $i<count($obj['results']); $i++) {
echo "" . $obj['results'][$i]['name'] . ";" . $obj['results'][$i]['vicinity'] . ";" . $obj['results'][$i]['geometry']['location']['lat'] . ";" . $obj['results'][$i]['geometry']['location']['lng'] . ";" . $obj['results'][$i]['place_id'] . DISPLaY POSTCODE "<BR>";
};
this is one ex response from the first request, the ChIJidzOXaLBpEcRxEKHcEN9fuo is the place id which i have to request the details:
Flinsberger Sportplatz;Heilbad Heiligenstadt;51.3163051;10.1929773;ChIJidzOXaLBpEcRxEKHcEN9fuo
this is api call shows the neede details, which i need and can access:
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJidzOXaLBpEcRxEKHcEN9fuo=name,rating,formatted_phone_number&key=YOUR_API_KEY
i need to include the 2nd request in the 1st, to get for ex. the postalcode for the specific item, which is my problem i dont know.
and the result should be:
name,adress,postalcode, ... , ... ,...
Following the comments, I came up with this. Note that I do not have an API key myself to test, the the idea is there. You might have to adjust the reference to $obj2 based on the result of the json_decode function for the second query (the one in the loop).
<?php
$apikey = 'KEY';
$url1 = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.374,10.1495&rankby=distance&name=keyword&language=de&key=$apikey";
$json1 = file_get_contents($url1);
$obj1 = json_decode($json1, true);
for( $i = 0; $i < count($obj1['results']); $i++)
{
$place_id = $obj1['results'][$i]['place_id'];
$url2 = "https://maps.googleapis.com/maps/api/place/details/output?json&key=" .$apikey . "&placeid=" . $place_id . "&fields=address_component"
$json2 = file_get_contents($url2);
$obj2 = json_decode($json2, true);
echo "" . $obj1['results'][$i]['name'] . ";" . $obj1['results'][$i]['vicinity'] . ";" . $obj1['results'][$i]['geometry']['location']['lat'] . ";" . $obj1['results'][$i]['geometry']['location']['lng'] . ";" . $obj1['results'][$i]['place_id'] . $obj2['result']['address_components']['postal_code'] . "<br>";
};
?>
The idea is you get the information you want form $obj1 and $obj2 based on the results of the 2 queries.

Steam Market Image API

I got a new problem while working on my project.
I want to decode this (what I tried until now):
$items = array($_POST['eingabe']);
$strs = file_get_contents("https://open-market.io/api/search/?name=$items&appID=730&limit=5");
$json = json_decode($strs, true);
$picimage = $json['results'][0]['image'];
echo '<a class="test1">' . $picimage . '</a></div></br>';
I really don't know what I did wrong. Can someone please show me my mistake?
example for json:
https://open-market.io/api/search/?name=Chroma%20Case&appID=730&limit=5
implode your array and urlencode it.
<?php
$items = array('counter','age');
$strs = file_get_contents("https://open-market.io/api/search/?name=".urlencode(implode($items,','))."&appID=730&limit=5");
$json = json_decode($strs, true);
$picimage = $json['results'][0]['image'];
echo '<a class="test1"> ' . $picimage . "</a></div></br>";

Looping through CSV and parsing a JSON query using each result

So despite hours of fiddling I cannot understand why my JSON query only returns a result for the last line in the CSV/TXT files I am trying to parse.
Here is the code:
//Enter API Key Here
$api_key = 'AIzaSyB9Dq3w1HCxkS5qyELI_pZuTmdK8itOBHo';
$origin = 'RG12 1AA';
$output_type = 'json'; //xml or json
$csv_location = 'http://www.naturedock.co.uk/postcodes.csv';
//Do not edit
$base_url = 'https://maps.googleapis.com/maps/api/directions/';
$origin_url = '?origin=';
$destination_url = '&destination=';
$end_url = '&sensor=false&key=';
$page = join("",file("$csv_location"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$destination = $kw[$i];
echo $destination;
$raw_url = $base_url . $output_type . $origin_url . $origin . $destination_url . $destination . $end_url . $api_key;
$request_url = str_replace(' ', '', $raw_url);
$getJson = file_get_contents($request_url);
$routes = json_decode($getJson);
$result = $routes->routes[0]->legs[0]->distance->value;
echo $result . '<br>';
}
The result I get looks like this:
Distance by Post Code Generator v0.1 by Phil Hughes
RG12 0GA
RG12 0GB
RG12 0GC
RG12 0GD4066
Where the '4066' is the correct variable for RG12 0GD postcode but none of the others return results as you can see.
Please help.
Your
join("",file("$csv_location"));
concatenated all lines feom the file to a single line without separator. The following explode() sees no newlines any more. So you are working on one line only. count($kw) always evaluates to 1 and your loop runs only one time.

PHP & JSON Parsing

I have read a few Q&As on here and additional articles, but cannot get this script to display the relevant values from the JSON return (which are long and lat from this Google Maps call).
<?php
// Address for Google to search
$address = 'London,UK';
// Get the map json data from Google Maps using the $address variable
$googleCall = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false';
$json = file_get_contents($googleCall);
//header("Content-type: application/json");
//echo $json;
echo $json->results->geometry->location->lat;
echo $json->results->geometry->location->lng;
?>
I am sure I am 99% there, just cannot see where the error is.
You can decode your json as an associative array and the access to all data with scopes
$address = 'London,UK';
$googleCall = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false';
$json = file_get_contents($googleCall);
$array = json_decode($json, true); //note second parameter on true as we need associative array
echo $array['results'][0]['geometry']['location']['lat'] . '<br>';
echo $array['results'][0]['geometry']['location']['lng'];
This will output
51.5112139
-0.1198244
try this out:
<?php
// Address for Google to search
$address = 'London,UK';
// Get the map json data from Google Maps using the $address variable
$googleCall = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false';
$json = file_get_contents($googleCall);
$json = json_decode($json);
//header("Content-type: application/json");
//echo $json;
echo $json->results->geometry->location->lat;
echo $json->results->geometry->location->lng;
?>
use json_decode here documentation
http://php.net/manual/en/function.json-decode.php
<?php
// Address for Google to search
$address = 'London,UK';
// Get the map json data from Google Maps using the $address variable
$googleCall = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $address .'&sensor=false';
$json = file_get_contents($googleCall);
$json = json_decode($json);
echo $json->results[0]->geometry->location->lat;
echo $json->results[0]->geometry->location->lng;
?>

Retrieve a Get Http request in php

I need to retrieve a get http request in php and store it in a variable.
I need to execute the following:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials
I know this is simple. just not able to get my head around it.
$content = file_get_contents('https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials');
Within the Open Graph protocol page on Facebook, there is an example within the documentation coded using PHP: http://developers.facebook.com/docs/opengraph/
<?php
$ogurl = "INSERT_YOUR_OG_URL_HERE";
define(FACEBOOK_APP_ID, "YOUR_APP_ID_HERE");
define(FACEBOOK_SECRET, "YOUR_SECRET_KEY_HERE");
$mymessage = "Hello World!";
$access_token_url = "https://graph.facebook.com/oauth/access_token";
$parameters = "grant_type=client_credentials&client_id=" . FACEBOOK_APP_ID ."&client_secret=" . FACEBOOK_SECRET;
$access_token = file_get_contents($access_token_url . "?" . $parameters);
$apprequest_url = "https://graph.facebook.com/feed";
$parameters = "?" . $access_token . "&message=" . urlencode($mymessage) . "&id=" . $ogurl . "&method=post";
$myurl = $apprequest_url . $parameters;
$result = file_get_contents($myurl);
// output the post id
echo "post_id" . $result;
}
?>
The key line in actually making the call being:
$result = file_get_contents($myurl);
There is also a good amount of other information about the resulting object you get back there that would be good to take a look into.
Hope this is helpful.
if ($fp = fopen('https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials', 'r')) {
$content = '';
// keep reading until there's nothing left
while ($line = fread($fp, 1024)) {
$content .= $line;
}
// do something with the content here
// ...
} else {
// an error occured when trying to open the specified url
}
You mean something like
$client_id = $_GET['client_id'];
$client_secret = $_GET['client_secret'];
$grant_type = $_GET['grant_type'];
?
Or rather something like
$content = file_get_contents($url);
?
Use the following
$id = $_GET['client_id'];
$type = $_GET['grant_type'];
$secret = $_GET['client_secret'];
Hope this helps you

Categories