2013-11-07 2 views
1

До вчерашнего дня у меня был отлично работающий сайт/приложение организатора бюджета, работающее с iGoogle.Получение данных конвертации валют от Yahooapis теперь, когда iGoogle ушли

через PHP, используя следующую небольшую линию

file_get_contents('http://www.google.com/ig/calculator?hl=en&q=1usd=?eur'); 

и подобное я был в состоянии получить все, что нужно.

На сегодняшний день это больше не работает. Когда я рассмотрел этот вопрос, произошло то, что Google ушел в отставку iGoogle. Вот досада!

В любом случае, я искал в другом месте, но я не могу найти ничего, что бы соответствовало моим потребностям. Я бы ДЕЙСТВИТЕЛЬНО любил просто исправить это и снова запустить его, просто переключив одну строку кода (т. Е. Изменив адрес Google с адресом другого доступного API-интерфейса), но похоже, что никто этого не делает.

API от rate-exchange.appspot.com кажется, что он может быть аналогом iGoogle, но, увы, он никогда не работает. Я продолжаю получать сообщение «Over Quota».

(Здесь приходит первый вопрос: кто-нибудь там знают простого, надежного, iGoogle-сортировка API?)

Поэтому я предполагаю, что естественная вещь будет функция Yahoo YQL (по крайней мере, я полагаю, это является столь же надежным).

запросов Yahoo, выглядеть следующим образом:

http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN")&env=store://datatables.org/alltableswithkeys 

То, что я действительно не могу понять, как анализировать эти данные. Он выводит XML.

То, что я имел обыкновение иметь это:

function exchange($inputAmount,$inputCurrency,$outputCurrency) { 
    $exchange = file_get_contents('http://www.google.com/ig/calculator?hl=en&q='.$inputAmount.$inputCurrency.'=?'.$outputCurrency); 
    $exchange = explode('"', $exchange); 
    $exchange = explode('.', $exchange['3']); 
    $exchange[0] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[0])); 
    if(isset($exchange[1])){ 
     $exchange[1] = str_replace(" ", "",preg_replace('/\D/', '', $exchange[1])); 
     $exchange = $exchange[0].".".$exchange[1];   
    } else{ 
     $exchange = $exchange[0]; 
    } 
    return $exchange; 
} 

Таким образом, пользователь был в состоянии получить курс от входной валюты, такие как «USD», и выходной валюты, такие как «евро» на конкретный количество денег. Как я уже сказал, это работало до вчерашней ночи.

Любые идеи?

ответ

2

Ничего! Решила!

Для тех, кто заинтересован, вот что я сделал, чтобы получить код для работы (с наименьшим chnges возможно) с Yahoo YQL:

// ** GET EXCHANGE INFO FROM YAHOO YQL ** // 
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "EURUSD")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need). 
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable. 
$exchange = array(); //<-- Build an array to hold the data we need. 
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for). 
    $name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR"). 
    $rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion. 
    $exchange[$name] = $rate; //<-- Put the data pairs into the array. 
endfor; //<-- End for loop. :) 
// ** WORK WITH EXCHANGE INFO ** // 
$toeur = array(//<-- Create new array specific for conversion to one of the units needed. 
     'usd' => $exchange['USD to EUR'], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name. 
     'eur' => 1); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert" 
$tousd = array(
     'eur' => $exchange['EUR to USD'], 
     'usd' => 1); 

Это в основном все, что вам нужно, чтобы получить все информацию об обмене, которую вы хотите. После этого, вы используете его все что-то вроде этого:

amount*$toxxx['coin']; 

Таким образом, сказать, что я хотел бы знать, сколько евро 100 USD прямо сейчас:

100*$toeur['usd']; 

Кусок торта!

0

Еще очень полезное решение QuestionerNo27. Однако с начала 2015 года Yahoo YQL, по-видимому, немного изменил вывод XML своих api.«Не имя» теперь больше не переводит в строку, как «USD в EUR», а «USD/EUR» и должен в коде выше можно ссылаться следующим образом:

$toeur = array( 
    'usd' => $exchange['USD/EUR'] 

вместо

$toeur = array( 
    'usd' => $exchange['USD to EUR'] 

и аналогичным образом для других конверсий валют.

0

Я создал процедуру, чтобы конвертировать валюту на основе @ QuestionerNo27 http://jamhubsoftware.com/geoip/currencyconvertor.php?fromcur=USD&tocur=EUR&amount=1 вы можете потреблять этот

<?php 
$fromcur = $_GET['fromcur']; 
$tocur = $_GET['tocur']; 
$amt = $_GET['amount']; 
// ** GET EXCHANGE INFO FROM YAHOO YQL ** // 
$url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("'.$fromcur.$tocur.'")&env=store://datatables.org/alltableswithkeys'; //<-- Get the YQL info from Yahoo (here I'm only interested in converting from USD to EUR and vice-versa; you should add all conversion pairs you need). 
$xml = simplexml_load_file($url) or die("Exchange feed not loading!"); //<-- Load the XML file into PHP variable. 
$exchange = array(); //<-- Build an array to hold the data we need. 
for($i=0; $i<2; $i++): //<-- For loop to get data specific to each exchange pair (you should change 2 to the actual amount of pairs you're querying for). 
    $name = (string)$xml->results->rate[$i]->Name; //<-- Get the name of the pair and turn it into a string (this looks like this: "USD to EUR"). 
    $rate = (string)$xml->results->rate[$i]->Rate; //<-- Do the same for the actual rate resulting from the conversion. 
    $exchange[$name] = $rate; //<-- Put the data pairs into the array. 
endfor; //<-- End for loop. :) 
// ** WORK WITH EXCHANGE INFO ** // 
$conv = $fromcur . '/' . $tocur; 
$toeur = array(//<-- Create new array specific for conversion to one of the units needed. 
     $tocur => $amt*$exchange[$conv], //<-- Create an array key for each unit used. In this case, in order to get the conversion of USD to EUR I ask for it from my $exchange array with the pair Name. 
     $fromcur => $amt, 
     "ex_amt" =>$amt*$exchange[$conv]); //<-- The way I coded the app, I found it more practical to also create a conversion for the unit into itself and simply use a 1, which translates into "do not convert" 

echo json_encode($toeur); 

?>