B
B
Boris Shpakovsky2018-02-08 01:19:35
PHP
Boris Shpakovsky, 2018-02-08 01:19:35

I want to understand the code of this script. How to pull an element from the array in this example?

$file = simplexml_load_file("http://www.cbr.ru/scripts/XML_daily.asp?date_req=".date("d/m/Y"));
  
  $valutes = array();
  
  foreach ($file AS $el){
      $valutes[strval($el->CharCode)] = strval($el->Value);
  }
  print_r($valutes);

The code is quite simple, but as a beginner it's hard for me to figure it out. This script displays exchange rates for today from the XML file of the Central Bank. Please help me figure out what is happening in this example and pull out only USD and EUR from the array.
What I understand so far:
First, the xml file itself is loaded and presented as an object and declared as the $file variable. Then the variable $valutes is declared, which is an array. Then the array is iterated over and then I have difficulty understanding the logic of what is happening. Why is $file as $el, and why is the first line in square brackets here, but not the second: "$valutes[strval($el->CharCode)] = strval($el->Value);"?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2018-02-08
@kotboris

Why $file as $el
Because they sort through all the values ​​​​from file in turn, this is how this foreach works.
why is the first line enclosed in square brackets, but the second is not?
Because they write data to an associative array , where CharCode will be the key and Value will be the value.

M
Mykola Ivashchuk, 2018-02-08
@mykolaim

Here and there

O
Oleg Lysenko, 2018-02-08
@oleglysenko

$file in your case is not an array, but a SimpleXMLElement object, it is filled with data from an xml file, the SimpleXMLElement class itself implements the Traversable interface , which allows it to be used in a foreach loop, $el is also an object of the SimpleXMLElement type, its fields can be accessed directly, like $el->CharCode, it works through the __get() magic method. __toString() is a method that casts a SimpleXMLElement object to a string.
To understand in more detail how it works and what is inside, look into the SimpleXMLElement class and see what is there, then it will become clearer.
As for the code, you can write something like this:

$file = simplexml_load_file("http://www.cbr.ru/scripts/XML_daily.asp?date_req=" . date("d/m/Y"));

        $values = [];

        foreach ($file as $el) {
            if ($el->CharCode == 'USD' || $el->CharCode == 'EUR') {
                $values[$el->CharCode->__toString()] = $el->Value->__toString();
            }
        }
        print_r($values);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question