0

我正在尝试掌握 preg_match 的窍门,但我无法使用正则表达式选择我想要的内容。

我正在使用此处找到的 XML 提要http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml

我想找到一种货币和它的价值。它作为数组打印,所以我很困惑如何做到这一点。我需要以某种方式循环吗?即使我这样做了,我仍然没有弄清楚 preg_match 部分。

<?
$xml = simplexml_load_file('http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml');
//print_r($xml);

preg_match('/ USD \= \(([0-9\.\,]+)\)$/',$xml,$match);

echo $match[1];
echo $match[2];

?>

任何帮助,将不胜感激!

编辑 - 我试图让 PHP 网站上的示例使用我的链接工作,但我遇到了一堆错误。这就是我所拥有的

<?

$string = simplexml_load_file('http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml');

$xml = new SimpleXMLElement($string);

$result = $xml->xpath('b/c');

while(list( , $node) = each($result)) {
   echo 'b/c: ',$node,"\n";
}
?>
4

2 回答 2

2

您正在使用 SimpleXML 库,因此您可以使用xpath 函数

更简单的解决方案是遵循(this)描述:

$xml = simplexml_load_file('http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml');

foreach($xml->Cube->Cube->Cube as $rate){
  if ($rate["currency"] == 'WANTED CURRENCY') {
    echo $rate["rate"].' '.$rate["currency"].'<br/>';
  }
}
于 2012-05-27T22:30:53.193 回答
1

如果你想使用正则表达式,你可以试试这个表达式吗?

USD' rate='(.*)'

我喜欢在帮助我表达时使用这个网站:http: //gskinner.com/RegExr/

在这种情况下,我使用 file_get_contents 获取了 xml 的内容,将它们粘贴到此站点的框中,然后使用页面顶部的栏开始制作表达式。当您键入时,您会自动在下面的框中查看是否有任何匹配项。

于 2012-05-27T22:37:50.537 回答