所以,我正在做一項任務,我需要獲取歐元 - 美元之間的當前貨幣兌換,我必須使用 PHP 并且以前從未使用過它,所有資料都可以在本網站https://www.ecb.europa 上找到。 eu/stats/eurofxref/eurofxref-daily.xml?5105e8233f9433cf70ac379d6ccc5775
到目前為止我的代碼是
`<php
ini_set('default_charset', 'UTF-8');
$url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml?5105e8233f9433cf70ac379d6ccc5775";
$xml = simplexml_load_file($url);
echo $xml->Cube;
foreach ($xml as $record) {
print_r($record);
}
?>`
對我來說,輸出真的很令人困惑,因為它顯示的是陣列,標簽有“:”,比如“gesmes:Envelope”,我不知道該怎么做,任何幫助表示贊賞!
uj5u.com熱心網友回復:
XML 確實有點令人困惑。
我之前有過這個話題,所以我可以給你一個有效的例子:
編輯:我不確定你的 url 上的哈希標簽是什么。我認為你不需要它。
ini_set('default_charset', 'UTF-8');
$url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml?5105e8233f9433cf70ac379d6ccc5775";
$xml = simplexml_load_file($url, 'SimpleXMLElement', LIBXML_NOCDATA);
if (!$xml instanceof \SimpleXMLElement) {
throw new \Exception("Cannot get currency rates. Cannot parse Xml.");
}
if (!isset($xml->Cube->Cube->Cube)) {
throw new \Exception("Cannot get currency rates. Xml path wrong.");
}
$rates = [];
foreach ($xml->Cube->Cube->Cube as $rate) {
$rates[strtoupper((string)$rate['currency'])] = (float)$rate['rate'];
}
echo var_export($rates, true) . PHP_EOL;
結果:
// array (
// 'USD' => 1.1271,
// 'JPY' => 128.22,
// 'BGN' => 1.9558,
// 'CZK' => 25.413,
// 'DKK' => 7.4366,
// 'GBP' => 0.83928,
// 'HUF' => 367.8,
// 'PLN' => 4.6818,
// 'RON' => 4.9495,
// 'SEK' => 10.096,
// 'CHF' => 1.0462,
// 'ISK' => 147.8,
// 'NOK' => 10.0483,
// 'HRK' => 7.516,
// 'RUB' => 82.8124,
// 'TRY' => 12.5247,
// 'AUD' => 1.5581,
// 'BRL' => 6.268,
// 'CAD' => 1.4254,
// 'CNY' => 7.2027,
// 'HKD' => 8.7832,
// 'IDR' => 16105.54,
// 'ILS' => 3.4887,
// 'INR' => 83.6905,
// 'KRW' => 1344.64,
// 'MXN' => 23.4637,
// 'MYR' => 4.7152,
// 'NZD' => 1.6098,
// 'PHP' => 57.073,
// 'SGD' => 1.5344,
// 'THB' => 36.969,
// 'ZAR' => 17.7513,
// )
編輯 2:你也可以看看https://api.exchangerate.host/。
僅美元https://api.exchangerate.host/latest?base=EUR&symbols=USD
通話示例:所有人通話示例:https://api.exchangerate.host/latest?base=EUR
當我沒記錯時,您可以使用日期(歷史)而不是latest.
uj5u.com熱心網友回復:
您可以使用 XPath 直接選擇您感興趣的值:
$url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml?5105e8233f9433cf70ac379d6ccc5775";
$xml = simplexml_load_file($url);
$xml->registerXPathNamespace('c', "http://www.ecb.int/vocabulary/2002-08-01/eurofxref");
$currencyTarget = 'USD' ;
// look at all Cube elements (everywhere in the document)
// that have a attribute 'currency' equals to 'USD',
// and returns its rate attribute
$rates = $xml->xpath("//c:Cube[@currency = '$currencyTarget']//@rate");
// xpath returns an array, select the first (and unique) element, and convert the attribute to double
$rate = doubleval($rates[0]) ;
var_dump($rate); // float(1.1271)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/361027.html
