-1

How do I get the value 1 with PHP and SimpleXML out of the following xml file?

data.xml

<users>
 <user name="test">
  <option name="enabled">1</option>
  <option name="setting">on</option>
 </user>
</users>

test.php

$file = 'data.xml';
$xml = simplexml_load_file($file);

foreach ($xml->users->user->option as $option) {
 echo $option['name'];
}

Output

enabledsetting

How do I output the value?

PhilG
  • 161
  • 2
  • 10

2 Answers2

1

Possible solution without if or switch is using XPath :

$xml = new simplexml_load_file($file);
foreach ($xml->xpath('//option[@name="enabled"]') as $option) {
    echo $option;
}

Above XPath expression means, find all <option> nodes having attribute name value equals enabled.

har07
  • 88,338
  • 12
  • 84
  • 137
0

Found the result:

test.php

$file = 'data.xml';
$xml = simplexml_load_file($file);

foreach ($user->option as $option) {
 if ((string) $option['name'] == 'enabled') {
  echo $option;
 }
}

Is there a solution to get it without "if" or "switch"?

PhilG
  • 161
  • 2
  • 10