1

I am getting some exchange rate data and would like to access the variable outside of the for loop. My current code only results in:

1: 0.82910

but my expected result is:

1: 0.82910

2: 0.82910

I am wondering why this variable is not accessible outside of the loop and how can I make it accessible?

My code (Sorry if the code is bad, Im new to PHP)

$vExchaRates = file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

$xml = simplexml_load_string($vExchaRates);

for ($i = 1; $i <= 32; $i++) {
    if ($xml->Cube[0]->Cube[0]->Cube[$i]->attributes()->currency == "GBP") {
        $vGBPERate = $xml->Cube[0]->Cube[0]->Cube[$i]->attributes()->rate;
        echo "1: " . $vGBPERate . "\r\n";
    }
}

echo "2: " . $vGBPERate;

Thank you for any help you can provide.

2
  • no errors? it doesn't look like your code is even reaching the other side of the loop if you don't even see "2: " Commented Jan 26, 2014 at 8:10
  • What happens if you add . "\r\n" to the second echo? Commented Jan 26, 2014 at 8:14

2 Answers 2

4

You need to check if object $xml->Cube[0]->Cube[0]->Cube[$i] isset or not.

$vExchaRates = file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
$xml = simplexml_load_string($vExchaRates);

for ($i = 1; $i <= 32; $i++) {
    if (isset($xml->Cube[0]->Cube[0]->Cube[$i]) && $xml->Cube[0]->Cube[0]->Cube[$i]->attributes()->currency == "GBP") {
        $vGBPERate = $xml->Cube[0]->Cube[0]->Cube[$i]->attributes()->rate;
        echo "1: " . $vGBPERate . "\r\n";
   }
}    
echo "2: " . $vGBPERate;

Demo.

Note: Turn on your errors using ini_set("display_errors",1) to get such errors or notices.

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

2 Comments

+1. Probably the errors is turned off, and he just see first echo.
This has worked, I will accept this answer :) Thank You for your help. This is hosted php so I am unable to edit the php.ini.
0

It looks like the 32 was too large and number and is throwing it off. It might be better to use foreach instead. It works perfectly:

$vExchaRates = file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

$xml = simplexml_load_string($vExchaRates);

foreach($xml->Cube[0]->Cube[0]->Cube as $a)
{

    if ($a->attributes()->currency == "GBP") {
        $vGBPERate = $a->attributes()->rate;
        echo "1: " . $vGBPERate . "\r\n";
}
}

echo "2: " . $vGBPERate;

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.