0

Using the following xml: http://www.bnr.ro/nbrfxrates.xml

How can I get the EUR value?

Been trying like this ... but no luck.

            $xmlDoc = new DOMDocument();
            $xmlDoc->load('http://www.bnr.ro/nbrfxrates.xml');

            $searchNode = $xmlDoc->getElementsByTagName("Cube");

            var_dump($searchNode);

            foreach ($searchNode as $searchNode) {
                $valueID = $searchNode->getAttribute('Rate');

                echo $valueID;

            }
1
  • Cube tag hasn't Rate attribute. Do you mean date attribute or Rate child? Commented Oct 12, 2016 at 9:18

3 Answers 3

1

Check this

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load('http://www.bnr.ro/nbrfxrates.xml');


foreach ($xmlDoc->getElementsByTagName('Rate') as $searchNode) {
    if($searchNode->getAttribute('currency') === 'EUR') {
        echo $searchNode->nodeValue;
    }
}

?>
Sign up to request clarification or add additional context in comments.

Comments

1

First Rate is not an attribute but an element. So you would need another getElementsByTagName('Rate') and loop over it. However the XML uses a default namespace so getElementByTagNameNS('http://www.bnr.ro/xsd', 'Rate') would be the correct way.

An easier way is to use Xpath to fetch the value directly:

$document = new DOMDocument();
$document->load('http://www.bnr.ro/nbrfxrates.xml');
$xpath = new DOMXpath($document);
$xpath->registerNamespace('r', 'http://www.bnr.ro/xsd');

var_dump(
  $xpath->evaluate('number(//r:Cube/r:Rate[@currency="EUR"])')
);

Output:

float(4.4961)

Xpath does not have a default namespace, so you have to register your own alias for it (I used r in the example.).

The Xpath expression

  • fetch any {http://www.bnr.ro/nbrfxrates.xml}Cube
    //r:Cube
  • fetch all {http://www.bnr.ro/nbrfxrates.xml}Rate children
    //r:Cube/r:Rate
  • filter by the currency attribute
    //r:Cube/r:Rate[@currency="EUR"]
  • cast the first found node into a number
    number(//r:Cube/r:Rate[@currency="EUR"])

1 Comment

Thank you for the explanation. I ll give it a try.
0
<?php
    $xmlDoc = new DOMDocument();
    $xmlDoc->load('http://www.bnr.ro/nbrfxrates.xml');

    foreach($xmlDoc->getElementsByTagName("Rate")  as $node)
    {
        $currency = $node->getAttribute('currency');
        if($currency == 'EUR')
        {
             $value = $node->nodeValue;
        }
    }
    echo 'value for EUR is - '. $value;

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.