How to cache multiple imdb rating results - php

I'm trying to make a movie list where is movie name and I'm trying to get imdb ratings, from url (database) and code works. But my problem is that if I have 50 movies in the list, this code makes 50 different omdb api calls and it slows down my site very well.
So how I can store/cache ratings? I'm not good for cache thins at all. Thanks :)
if (($row["imdb"] != "") AND (strpos($row["imdb"],'imdb')) AND
(strpos($row["imdb"],'title'))) {
$imdbID = ltrim(strrchr($row["imdb_url"],'tt'),'tt');
$imdbID = preg_replace("/[^A-Za-z0-9]/", "", $imdbID);
$omdbapi_key = 'API_KEY';
$url = file_get_contents("https://www.omdbapi.com/?i=tt" . $imdbID . "&apikey=" . $omdbapi_key);
$omdb = json_decode($url, true);
$imdb_rating = "<a target='_blank' href='https://www.imdb.com/title/tt" . $imdbID . "'>Rating: " . $omdb['imdbRating'] . " / 10</a>";
Now I can write cache file for just one movie. I don't know how I can add multiple movie api calls in one file. I have form where I add movie (Title, imdb url). I think I need rewrite whole file when I add new movie.
Update:
$cacheFile = 'cache' . DIRECTORY_SEPARATOR . md5($url);
if( file_exists($cacheFile))
{
$omdb = json_decode(file_get_contents($cacheFile), true);
}
else
{
$url = file_get_contents("https://www.omdbapi.com/?i=tt".$imdbID."&apikey=" . $omdbapi_key);
file_put_contents($cacheFile, $url);
$omdb = json_decode($url, true);
}

Related

How to construct url with http_build_query, but display values without variables?

I'm trying to generate an URL from all values of two arrays by using http_build_query:
Array 1:
$server = array($_GET["server"]);
Array 2:
$data = array($_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"],);
The code for generating URL I currently have written:
$server = array(''=>$_GET["server"]);
$data = array($_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"],);
$url = '.tile.openstreetmap.org';
$saite = http_build_query($server). $url ."/". http_build_query($data,'','/').".png";
Here's the URL made of code above:
=c.tile.openstreetmap.org/0=6/1=90/2=110.png
Here's the structure of url I'm trying to make:
c.tile.openstreetmap.org/6/90/110.png
I have reviewed some other posts about this topic like this one and this, but those posts aren't completely useful for solving my problem.
So I hope someone with greater knowledge could show me a solution or at least a hint how to get closer to solution.
You could use implode():
$server = $_GET["server"];
$data = [$_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"]];
$url = '.tile.openstreetmap.org';
$saite = "$server/$url/" . implode('/', $data) . ".png";
I'm not sure about some things in this code, but the implode() should do the job.
You are using http_build_query in the wrong way. You just don't need that. There are 2 options, you may use any one of them.
Use implode(), the simplest way to do the job.
$server = array(
'' => $_GET['server']
);
$data = array(
$_GET['z_koord'],
$_GET['x_koord'],
$_GET['y_koord'],
);
$url = $server . '.tile.openstreetmap.org';
$saite = $url . '/' . implode("/", $data) . '.png';
Directly create the URL using the Parameters as shown here:
$url = '.tile.openstreetmap.org' .;
$saite = $_GET['server'] . $url . '/' . $_GET['z_koord'] .'/'. $_GET['x_koord'] . '/'.$_GET['y_koord'] . '.png';

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.

Sharing a URL within a tweet

I want a link to appear within a twitter tweet. At the moment the raw HTML comes out.
click here to test
Here is my code.
$url = 'www.google.com'
$text = urlencode( "click here to test" )
$share = 'http://twitter.com/share';
$url = '?url=' . $url;
$text = '&text=' . $title;
$hashtag = '&hashtags=' . $hashtag;
$url = $share . $url . $text . $hashtag;
Without urlencode() the actual twitter icon then spits out HTML text everywhere on my page.
twitter auto converts url. but i dont think you can do anything more than what stated here because of anti spam policy. https://support.twitter.com/articles/78124

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.

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