使用正则表达式从xml获取货币值

时间:2013-07-06 23:30:36

标签: php regex

我需要通过代码'USD'或id'R01235'

来获取USD等某种货币的价值

我接下来尝试,但它不是那么正确

<?php
$pattern = 'USD.*(\\d{2},\\d{4})';
$subject = '<Valute ID="R01215"> 
<NumCode>208</NumCode> 
<CharCode>DKK</CharCode> 
<Nominal>10</Nominal> 
<Name>Danish kroner</Name> 
<Value>57,4385</Value> 
</Valute> 
<Valute ID="R01235"> 
<NumCode>840</NumCode> 
<CharCode>USD</CharCode> 
<Nominal>1</Nominal> 
<Name>U.S. dollar</Name> 
<Value>33,2247</Value> 
</Valute> 
<Valute ID="R01239"> 
<NumCode>978</NumCode> 
<CharCode>EUR</CharCode> 
<Nominal>1</Nominal> 
<Name>Euro</Name> 
<Value>42,8399</Value> 
</Valute>';
$result = preg_match( $pattern, $subject , $matches );
echo $result;
print_r($matches);
?>

1 个答案:

答案 0 :(得分:1)

改为做一些简单的XML解析。

$simplexml = new SimpleXMLElement("<root>$xml</root>");
foreach ($simplexml->Valute as $valute) {
    if ("$valute->CharCode" == 'USD') {
        $result = "$valute->Value";
    }
}