PHP - 从XML提要中获取数据

时间:2016-02-29 09:18:56

标签: php xml-parsing

我有以下代码:

<?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") {
}

但这暂时不起作用

2 个答案:

答案 0 :(得分:0)

感谢Robbie的链接:

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

答案 1 :(得分: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];