if i have this xml :
<field name="gender" type="select1">
<label>Gender</label>
<item>
<label>Male</label>
<value>1</value>
</item>
<item>
<label>Female</label>
<value>2</value>
</item>
<constraints>
<required/>
</constraints>
</field>
assume that i have to get each item tags and create a html form . how can i do that using simplexml document print_r of xml object shows this :
[item] => Array
(
[0] => SimpleXMLElement Object
(
[label] => Male
[value] => 1
)
[1] => SimpleXMLElement Object
(
[label] => Female
[value] => 2
)
)
but in my code
foreach($xml as $field)
{
$type = $xml->field[$i]->attributes()->type ;
$name = $xml->field[$i]->attributes()->name ;
$required = $xml->field[$i]->constraints[0]->required[0] ;
//checkboxes and radios
echo $xml->field[$i]->lable ;
//check the lable
if(is_array($xml->field[$i]->item))
{
echo 'yes it\'s a array ' ;
}
$i++ ;
}
using this code
if ($type == 'select1' || $type == 'radio') {
foreach ($field->item as $item) {
echo "{$item->label} = {$item->value}
";
}
}
actually there is another sets of field tag consist of item tags so second foreach loop will be ignored
<field name="language" type="select">
<label>Language(s)</label>
<item>
<label>English</label>
<value>1</value>
</item>
<item>
<label>French</label>
<value>2</value>
</item>
<item>
<label>Persian</label>
<value>4</value>
</item>
<constraints/>
</field>
You have to do something like this:
$sxml = new SimpleXMLElement($xml);
foreach ($sxml->field as $field) {
$label = $field->label;
$type = $field['type'];
$name = $field['gender'];
$required = isset($field->constraints->required);
if ($type == 'select1' || $type == 'radio') {
foreach ($field->item as $item) {
echo "{$item->label} = {$item->value}
";
}
}
}
If there are not any <items>
nodes, the second foreach
will be ignored. You don't have to explicitly check for it.