2016-02-29 100 views
0

獲取數據我有以下代碼:PHP - 從XML飼料

<?php 

    $url = 'http://www.floatrates.com/daily/gbp.xml'; 
    $xml = simplexml_load_file($url) or die("feed not loading"); 

    foreach ($xml as $val) { 
    echo "<pre>" . print_r($val) . "</pre>"; 
    } 

?> 

,其輸出的這些負載(1元貨幣):

SimpleXMLElement Object ([title] => 1 GBP = 1.39687377 USD [link] => http://www.floatrates.com/gbp/usd/ [description] => 1 U.K. Pound Sterling = 1.39687377 U.S. Dollar [pubDate] => Mon, 29 Feb 2016 00:00:01 GMT [baseCurrency] => GBP [baseName] => U.K. Pound Sterling [targetCurrency] => USD [targetName] => U.S. Dollar [exchangeRate] => 1.39687377) 

如何搶只有美元嗎?然後提取匯率?

我已經試過

if ($val['targetCurrency'] == "USD") { 
} 

但是,這並不目前

+0

[看手冊](http://php.net/manual/en/simp lexml.examples-basic.php)爲基本用法的一個例子 –

回答

0

由於工作從羅比鏈接:

if ($val->targetCurrency == "USD") { 
    echo $val->exchangeRate; 
} 
0

您也可以使用XPath這樣做

$url = 'http://www.floatrates.com/daily/gbp.xml'; 
$xml = simplexml_load_file($url) or die("feed not loading"); 

$results = $xml->xpath('/channel/item/targetCurrency[.="USD"]/following-sibling::exchangeRate'); 

$exchangeRate = (float)$results[0];