G. Trennert
G. Trennert

Reputation: 571

how to get access to variable objects?

I have a question about access to object properties that will be used in a loop

I have an xml file withe a struture like this :

<labels>  
    <artiste01>  
        <label>Premiere image</label>  
        <label>Deuxieme image</label>  
    </artiste01>  
    <artiste02>  
        <label>Description 1</label>  
        <label>Description 2</label>  
    </artiste02>  
</labels>  

I read the file :

$label_file = file_get_contents('label_file.xml'); 
$label_xml = new SimpleXMLElement($label_file); 

Then I need to loop through any of the artistexx level.

$label_xml->artiste01->label[$i] works, but how can I reference the artistexx as a variable ?

Is this possible ? I can't figure out how to code this.

$obj->loopid->label[$i]

Upvotes: 1

Views: 63

Answers (2)

jon
jon

Reputation: 6246

does this work?

<?php

$label_file = file_get_contents('pikachoose/label_file.xml');
$label_xml = new SimpleXMLElement($label_file);

foreach($label_xml->labels->children() as $artist)
{
  echo $artist->getName();
}

?>

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227230

You can use {} to use a variable to get an object property.

Like this:

$a = '01';
echo $label_xml->{"artiste$a"}->label[0];

Or just use the variable as the property:

$a = 'artiste01';
echo $label_xml->$a->label[0];

Upvotes: 1

Related Questions