用PHP读取XML短符号值


Reading XML short notation value with PHP

如何使用PHP和SimpleXML从以下xml文件中获取值1

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'];
}

输出

启用设置

如何输出值?

没有ifswitch的可能解决方案是使用XPath:

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

上述XPath表达式表示,查找所有属性name值等于enabled<option>节点。

找到结果:

test.php

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

有没有一个解决方案可以在没有"if"或"switch"的情况下获得它?