I'm tinkering with GuzzleHTTP and API requests. I'm testing with Napiarfolyam.hu. They collect the exchange rates of different Valuta's in different Banks's.
Their API address: http://api.napiarfolyam.hu
They accept parameterised GET
requests
Possible parameters:
They say that their output should be this:
<arfolyam>
<valuta>
<item>
<bank>bank rövidítése</bank>//The bank's short name
<datum>mikor kapta ezt az értéket</datum>//Date
<penznem>pénznem kódja</penznem>//Currency
<vetel>árfolyam 1 egységre</vetel>//BuyPrice
<eladas>árfolyam 1 egységre</eladas>//SellPrce
</item>
</valuta>
<deviza>
<item>
<bank>bank rövidítése</bank>//The bank's short name
<datum>mikor kapta ezt az értéket</datum>//date
<penznem>pénznem kódja</penznem>//Currency
<vetel>árfolyam 1 egységre</vetel>//Buyprice
<eladas>árfolyam 1 egységre</eladas>//Sellprice
<kozep>árfolyam 1 egységre</kozep>//Middleprice only when the bank is MNB
</item>
</deviza>
</arfolyam>
My controller so far:
<?php
namespace App\Http\Controllers;
use DB;
use Carbon\Carbon;
use GuzzleHttp\Client;
class ValutaController extends Controller {
public function getValuta($bankName = '', $valuta = ''){
$client = new Client();
$response = $client->request('GET', "http://api.napiarfolyam.hu?bank={$bankName}&valuta={$valuta}");
$body = $response->getBody();
}
}
My problem: $body
is a string
and not an xml
. Why?
It would be better as an xml
or an array
becouse as I tinkered I saw that sometimes the BuyPrice
and SellPrice
are changed their place .
You can call Guzzle built-in xml()
function,
http://guzzle3.readthedocs.io/http-client/response.html#xml-responses
You can easily parse and use a XML response as SimpleXMLElement object using the xml() method of a response. This method will always return a SimpleXMLElement object if the response is valid XML or if the response body is empty. You will get an exception if you call this method and the response is not valid XML.
Here is your updated code
<?php
namespace App\Http\Controllers;
use DB;
use Carbon\Carbon;
use GuzzleHttp\Client;
class ValutaController extends Controller {
public function getValuta($bankName = '', $valuta = ''){
$client = new Client();
$response = $client->request('GET', "http://api.napiarfolyam.hu?bank={$bankName}&valuta={$valuta}");
$body = $response->xml();
}
}