Any idea how to connect to this API? - php

I tried to find any widget to show Tinkoof's bank currency rate, because it changes every 60sec., but nothing.
Finally I found this API, but there is no any documentation for it.
I tried to find any articles about parsing, but I guess there's no use in that because of absence of any tag.
I need to show the currency rate on my website via this API. Any idea?
Big thanks!

You just need to fetch the content You can use cURL or file_get_contents()
cURL version:
<?php
$url = "https://www.tinkoff.ru/api/v1/currency_rates";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$r = curl_exec($curl);
curl_close($curl);
$array = json_decode($r, true);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
file_get_contents version:
<?php
$r = file_get_contents('https://www.tinkoff.ru/api/v1/currency_rates');
echo "<pre>";
echo print_r(json_decode($r, true));
echo "</pre>";
?>
Both of them will work unless the remote website requires you to be human (has extra verifications to stop robot requests). cURL would be a better way if that were the case because you can fake a user agent using a header array.
Once you have the array build it's just a matter of accessing the required data. using $r as an array result of the remote json structure.

It looks pretty straightforward to me. For someone with a decent knowledge of PHP will do this, provided the output is:
Now with the above information, I would:
Get the result to PHP using file_get_contents().
Parse the result as an array using json_decode($contents, $true).
Using the above result, I would get display the value using: $output["payload"]["rates"][0]["buy"] or something similar.
At this time of writing, the above will get me 58:

Related

Using MediaWiki API with the Continue Command

I need some help Using the Mediawiki API with the "Continue" or "query-continue" Command to pull information from my wiki articles. I have a large number of wiki articles (more than 800 currently) and I need to use the api to pull them in batches of 50 and then print ou sections.
My API call works properly:
//Stackoverflow making me use a valid URL here, this api is actually my own localhost server
http://en.wikipedia.org/w/api.php?action=query&list=allpages&apfrom=a&apto=z&apnamespace=0&format=xml&aplimit=50 I am querying all pages, therefore "apfrom" and "apto".
I just need help processing the code with PHP and CURL accessing the API and processing the batches of 50 and using the "continue" to access more records until I hit the end. So far my php code is:
//the CURL commands here work and outputs a data set but only for the first 50 records, so I need to call "continue" to get to the end.
//My api url is localhost but I'm forced to use a valid URL by Stackoverflow.com
$url = sprintf('http://en.wikipedia.org/w/api.php?
action=query&list=allpages&apfrom=a&apto=z&apnamespace=0&format=xml&aplimit=50');
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'My site');
$res = curl_exec($ch);
$continue = '';
while ( // I don't know what to set here as true to get the while loop going, maybe continue = true? maybe set query-continue as true?)
{
//Maybe I need something other than $res['query-continue]??
if (empty($res['query-continue']))
{
exit;
}
else
{
$continue = '&apcontinue='.urlencode($res['query-continue']);
foreach ($res['query']['allpages'] as $v)
{
echo $v['title'];
}
}
}
Can someone correct my while loop code above so I can do a simple print out of the title from each wiki article in the loop? I've done a lot of searching online but I'm stuck!! I found a python loop example at http://www.mediawiki.org/wiki/API:Query but I have to do it in PHP. And I am not sure if I call continue or query-continue.
As svick said, please use a client library which handles continuation for you.
The query continuation mechanism has changed multiple times in MediaWiki, you don't want to understand it or even less rely on it.

Reading REST API Response in PHP

I am trying to read Raven SEO Tools API. It is a REST API and currently it is serving the data backup as an XML (or JSON if I choose) when I just request the URL through a web browser. What is the best method to get the response from their server into my own PHP script for me to then play around with.
Any help much appreciated
Cheers
If you only needs to retrieve a URL and parse its info. The easiest way is curl/JSON combination. Note that parsing JSON is faster than parsing XML.
http://www.php.net/manual/en/function.curl-exec.php
http://www.php.net/manual/en/function.json-decode.php
Something simple as:
$url = "http://api.raventools.com/api?key=B1DFC59CA6EC76FF&method=domains&format=json";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if(!$json) {
echo curl_error($ch);
}
curl_close($ch);
print_r(json_decode($json));
But if you need to call other methods from this API such as DELETE/PUT, etc. Then to have a REST client in PHP is more elegant solution. A comparison on those clients can be found in PHP REST Clients
I founded this code specifically for Raven API https://github.com/stephenyeargin/raventools-api-php
Sample code:
require 'path/to/raventools-api-php/raventools-api-php.class.php';
$Raven = new RavenTools( 'B1DFC59CA6EC76FF' );
$method = 'domains';
$options = array('format'=> 'json');
$responseString = $Raven->getJSON($method, $options);
print_r(json_decode($responseString));
cUrl
cUrl is a command line tool for getting or sending files using URL syntax.
curl -o example.html www.example.com
file_get_contents
<?php
$homepage = file_get_contents('http://www.example.com/api/parameters');
echo $homepage;
?>
Pecl's HTTPRequest class is a very nice client, I've been using it for a couple of Projects. http://pecl.php.net/package/pecl_http
Another pretty cool client is the Buzz client https://github.com/kriswallsmith/Buzz
It also plays nice with Symfony2 if that's of interest to you :)
You can use either one of them, but I think JSON is the easiest and more hassle-free, unless you use SimpleXML. The decision depends on the complexity of your data.
Given that the JSON returned by the API is valid you can convert it to an array or object by using PHP's json_decode() function.
<?php
# retrieve JSON from API here...
# i.e. it is stored in $data as a string
$object = json_decode($data);
$array = json_decode($data, true);
?>
In SimpleXML, it would be as follows:
<?php
$object = simplexml_load_string($data);
?>

Looping of a function is so time consuming

i have php function that parses a xml url and gives me an array.this functions uses a perticular id and gives all information related to that id which is passed in the form. now i have 20 different ids and i am passing these id's in this form using foreach loop like below
<?php
$relatedSlides = $result['RelatedSlideshows'];
if(!empty($relatedSlides)){
$k=1;
foreach($relatedSlides as $Related){
RelatedSlides($Related);
if($k%6==0){
echo '</tr><tr>';
}
$k++;
}
}
?>
This is the foreach loop. $relatedSlides is an array of all slide id's. Now I am writing the function that parses the information about a particular id.
function RelatedSlides($slideId){
$secret_key = 'my api key';
$ts=time();
$hash=sha1($secret_key.$ts);
$key = 'my secret key';
$url = 'http://www.slideshare.net/api/2/get_slideshow?api_key='.$key.'&ts='.$ts.'& hash='.$hash.'&slideshow_id='.$slideId.'&detailed=1';
echo $url;
$ch=curl_init() or die (curl_error());
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla Firefox');
$query = curl_exec($ch);
$errorCode = curl_errno($ch);
curl_close($ch);
$array = (array) simplexml_load_string($query);
//echo '<pre>';
//print_r($array);
//return $array;
echo "<font size=\"18\">return code is ".$errorCode."</font>";
echo '<td valign="top"><div id="slide_thumb"><img src=" '.$array['ThumbnailURL'].'" width="100" height="100"/></div><div id="slide_thum_des"><strong>Views:</strong>'.$array['NumViews'].'<br />'.$array['Title'].'....</div></td>';
}
When I call this function my connection times out every time. The function is absolutely correct. It gives all data about a particular id but when I run it in a foreach loop for many id's, "connection has been reset" or "connection timed out" displays.
You could try a couple of things:
Setup your curl handler outside of the RelateSlides() function. This way you don't have to keep building and tearing down the $ch resource every iteration.
Check the slideshare.net api and see if there are params you can pass to pull down smaller files.
As Luke wisely mentioned, you could make the page asyncronous, meaning you can render the page with 6 tiles, then have each tile make an ajax call for the slide you want. This way at least the user gets to see something while the tiles load, as opposed to being 'hung up' while you pull all the images at once.
I trust slideshare has a pretty robust cdn hosting these images, you may want to see if they have servers closer to your web server.
Quick question, is the curl option how slideshare.net suggested you go about pulling images? Chances are you could just create an image tag with a link directly to their api:
echo '<img src="http://www.slideshare.net/api/2/get_slideshow?api_key='.$key.'&ts='.$ts.'& hash='.$hash.'&slideshow_id='.$slideId.'&detailed=1' />';
If you are doing the curl option for extended data, you may want to consider caching the extended data so you don't have to keep making the extraneous simplexml_load_string call.
Timeout is due to your function taking its time as you have said already. It is normal, it also can be adjusted in either PHP config or Apache (don't remember, I would however check PHP config first). Remember that timeout is there for a reason - eg. good to time out when you run into inf loop - rare but possible.
I think one way to tackle this problem is to split this problem into parts and use AJAX to actually make individual calls that wont take as long.
eg.
Load the page with some JS/JQuery scripts.
Call async to get list of IDs (done by ajax call via jquery - the easiest)
Parse response (JSON?) on client side and do each request per each id async.
Wait for all results to come back and display them in a way you want.

Parsing PHP CURL data

I have been messing with CURL for the past day and I cannot seem to figure out how to parse out the return data. I know I could write a REGEX to extract data from the response but it seems like there is some function I am probably missing. Here is what I would like to try and do.
I want to make POST to a different domain and get back 3 things
1. the response headers
2. the response data
3. a session cookie
Is there a way I can get those 3 things back separately? right now I just get back a plain text response with the response header and the response data. I would like to be able to do something like
$Response = curl_exec($Curl_Connection);
$ResponseData = $Response['Data'];
$ResponseHeader = $Response['Header'];
ResponseCookie = $Response['Cookie'];
Does curl provide anything like this?
As I answered:
no post data returned when requesting headers CURLOPT_HEADER. PHP CURL
Add:
curl_setopt($Curl_Connection, CURLOPT_HEADER, TRUE);
$Response = curl_exec($Curl_Connection);
$curlHeaderSize=curl_getinfo($ch,CURLINFO_HEADER_SIZE);
$ResponseData = mb_substr($result, $curlHeaderSize);
$ResponseHeader = mb_substr($result, 0, $curlHeaderSize);
preg_match_all('|Set-Cookie: (.*);|U', $ResponseHeader, $content);
$ResponseCookie = implode(';', $content[1]);
According to the curl docs:
/* TRUE to include the header in the output. */
curl_setopt($Curl_Connection, CURLOPT_HEADER, TRUE);
So the header is added to the output of curl_exec command. I've been spitting this out and I don't see any way to retrieve the header separately from the response body. It gets worse when you start reading compressed output (zipped, inflated)
On top of that, it's a one big string, not an array, so in case you you want the header in a format like for example curl_getinfo brings back an array.
The easiest is to do this:
$backend_output = curl_exec($ch);
list( $backend_response_headers, $backend_response_body)
= explode("\r\n\r\n", $backend_output, 2);
That will split those 2 up, but you end up with a string for the response header, not an array which would be so much more helpful. Now making an arrray from that isn't so evident, even with a regex as you can't split on for example something simple like /(\w)\s:(\w)/ as ':' can occur in certain fields. It would be very cool if curl would offer the headers seperately but so far as I go through the docs, it doesn't seem to be there.
Concerning your session cookies, I believe you need to use CURLOPT_COOKIESESSION = true option for that, but I have less experience on cookies as I hardly ever have the professional need to use them. Good luck
update: The headers you can parse with http://php.net/manual/en/function.http-parse-headers.php or a custom function from the user comment section if you lack pecl.

Parsing iTunes json, then displaying it on webpage, and caching it with PHP

I'm working on a project where I need to get info from iTunes, cache it, and display it on a webpage with PHP. I prefer to use curl, since it seems faster, but I'm more familiar with get_file_contents. An example of the json url is http://itunes.apple.com/lookup?id=284910350. I'm able to grab and decode it, but I'm having trouble from there.
Here's my start:
<?php
$cas = curl_init('http://itunes.apple.com/lookup?id=284910350');
curl_setopt($cas, CURLOPT_RETURNTRANSFER, 1);
$jsonitunes = curl_exec($cas);
curl_close($cas);
$arr = json_decode($jsonitunes,true);
foreach($arr as $item) {
echo "kind: ". $item['kind'] ."<br>";
}
?>
I can print the array, or var_dump it, but can't seem to grab any values. After that, I need to cache the whole thing. If possible, I'd like to set it up to grab new content when it arrives, or on a frequent schedule without weighing down the server.
PHP Notice: Undefined index: kind in /var/www/html/frank/scratch.php on line 9
That should be your first clue (make sure you're logging notices somewhere where you can see them as you work). When you see that, you know you're referencing the array incorrectly.
Your next step should be
var_dump($arr);
to see where the key you're looking for actually is.
Then you should see that you actually need
foreach($arr['results'] as $item) {
Have you tried the json_decode function? You should be able to use cURL to download the contents of that page, store it in a variable, then use json_decode.
<pre>
<?php
$ch = curl_init("http://itunes.apple.com/lookup?id=284910350");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
$jsonDecoded = json_decode($content, true);
echo $jsonDecoded['results'][0]['artistName'];
?>
</pre>

Categories