Reputation: 161
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.
Upvotes: 1
Views: 137
Reputation: 985
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;
Upvotes: 0
Reputation: 26421
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;
Note: Turn on your errors using ini_set("display_errors",1)
to get such errors or notices.
Upvotes: 4