Php 无法访问for循环外部的变量
我正在获取一些汇率数据,希望访问for循环之外的变量。我当前的代码只会导致: 1:0.82910 但我的预期结果是: 1:0.82910 2:0.82910 我想知道为什么这个变量在循环之外是不可访问的,我如何使它可以访问 我的代码很抱歉,如果代码不好,我是PHP新手Php 无法访问for循环外部的变量,php,Php,我正在获取一些汇率数据,希望访问for循环之外的变量。我当前的代码只会导致: 1:0.82910 但我的预期结果是: 1:0.82910 2:0.82910 我想知道为什么这个变量在循环之外是不可访问的,我如何使它可以访问 我的代码很抱歉,如果代码不好,我是PHP新手 $vExchaRates = file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"); $xml = simplexml
$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;
感谢您提供的任何帮助。您需要检查对象$xml->Cube[0]->Cube[0]->Cube[$i]是否已设置
$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;
注意:使用ini\u setdisplay\u errors 1打开错误以获取此类错误或通知。您需要检查对象$xml->Cube[0]->Cube[0]->Cube[$i]是否已设置
$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;
注意:使用ini\u setdisplay\u errors,1打开您的错误,以获取此类错误或通知。看起来32太大和太多,正在将其丢弃。使用foreach可能更好。它可以完美地工作:
$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;
看起来32号太大了,而且数字太大了,要扔掉了。使用foreach可能更好。它可以完美地工作:
$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;
没有错误?如果你看不到2:如果你添加了,会发生什么\r\n到第二个回显?没有错误吗?如果你看不到2:如果你添加了,会发生什么\r\n到第二个回显?+1。可能错误被关闭了,他只看到第一个回声。这已经奏效了,我会接受这个答案:谢谢你的帮助。这是托管的php,因此我无法编辑php.ini.+1。可能错误被关闭了,他只看到第一个回声。这已经奏效了,我会接受这个答案:谢谢你的帮助。这是托管的php,因此我无法编辑php.ini。