-2

I have an xml file with something like this:

<itens>
<item>
  <name>Ball</name>
  <color1>Yellow</color1>
  <color2>Black</color2>
  <color3>Red</color3>
</item>

...

</itens>

I'm already looping it using simplexml_load_file and than a foreach. So I'm able to echo $item->color1 and get Yellow. But what I need is to loop through those colors, something like:

for($x = 1; $x < 4; $x++){
  echo $item->color.$x;
}

Thanks a lot!

1
  • 2
    Whoever created that XML format must have misunderstood something very badly about element names. However you access elements by their name in SimpleXML, and if you want to have that name in a variable, see the PHP manual. Or one of the duplicate questions (just selected one of them for you, here is another one: stackoverflow.com/q/13440244/367456). In the PHP manual it's here: php.net/manual/en/language.variables.variable.php Commented Jul 7, 2014 at 20:29

1 Answer 1

3
echo $item->color.$x;

Won't work because it simply echoes $item->color and then appends $x. Try this instead

echo $item->{'colour'.$x};
Sign up to request clarification or add additional context in comments.

1 Comment

I knew that my example wont work, it was just to explain. Also, thanks for the anwser. I'll check it as correct asap.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.