A
A
angelzzz2016-01-12 23:31:21
PHP
angelzzz, 2016-01-12 23:31:21

How to get data from xml?

There is an xml file:

<CurrencyRates Name="Daily Exchange Rates" Date="13.01.2016">
<Currency ISOCode="USD">
<Nominal>1</Nominal>
<Value>75,8985</Value>
</Currency>
<Currency ISOCode="EUR">
<Nominal>1</Nominal>
<Value>82,6117</Value>
</Currency>
</CurrencyRates>

I get data from it with this code
<?php
header('Content-type: text/html; charset=utf-8');
    $xml = simplexml_load_file('xml/daily.xml');
    echo $xml->CurrencyRates[Date];
    foreach ($xml->Currency as $Currency) {
        $number = $Currency->Value;
        echo '<span class="cur-code">'.$Currency[ISOCode].'</span>';
        echo '<span class="cur-val">'.substr("$number", 0, -2).'</span>'; /это потому-что я не смог преобразовать данные в число, решил просто обрезать два последних символа
    }

1. How to access the attribute Date="01/13/2016"?
2. How to convert the value value to a number and output it in a normal way with two decimal places?
3. How can you implement a comparison with the previous period?
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Евгений, 2016-01-12
@angelzzz

<?php
$xml = <<<XML
<CurrencyRates Name="Daily Exchange Rates" Date="13.01.2016">
<Currency ISOCode="USD">
<Nominal>1</Nominal>
<Value>75,8985</Value>
</Currency>
<Currency ISOCode="EUR">
<Nominal>1</Nominal>
<Value>82,6117</Value>
</Currency>
</CurrencyRates>
XML;

$xml = simplexml_load_string($xml);

echo $xml['Date'];
foreach ($xml->Currency as $Currency) {
    $number = $Currency->Value;
    echo '<span class="cur-code">' . $Currency['ISOCode'] . '</span>';
    echo '<span class="cur-val">' . sprintf('%.02f', str_replace(',', '.', $number)) . '</span>';
}

Владислав Старцев, 2016-01-13
@esvlad

Используй SimpleXMLElement::attributes
$xml->Currency->CurrencyRates->attributes('Date');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question