SimpleXML Dynamic element names

2020-04-21 07:14发布

问题:

echo $xml->SLOT1->Effect;
echo $xml->SLOT2->Effect;
echo $xml->SLOT3->Effect;

Is there a way to simplify this by using a for loop? I tried this but it echos nothing:

for ($x = 1; $x <= 3; $x++) {
   echo $xml->SLOT[$x]->Effect;
}

回答1:

You can use

$xml->{"SLOT".$x}->Effect;


回答2:

for ($x = 1; $x <= 3; $x++) {
   echo $xml->{SLOT.$x}->Effect;
}


标签: php simplexml