是否可以从以下xml结构创建数组:
<language>
<data section="Section 1">String 1</data>
<data section="Section 1">String 2</data>
<data section="Section 1">String 3</data>
<data section="Section 2">String 4</data>
<data section="Section 2">String 5</data>
<data section="Section 2">String 6</data>
<data section="Section 3">String 7</data>
<data section="Section 3">String 8</data>
<data section="Section 3">String 9</data>
</language>
$xmlel = simplexml_load_file("file.xml");
我想做的是使用:
$xmlel->xpath()
提取名为"section"的数据属性并转换为数组,预期结果应具有唯一值,如下所示:
[section] => Array
(
[0] => Section 1
[1] => Section 2
[2] => Section 3
)
要查找以获得唯一结果的 xpath 表达式是:
//data[not(@section = preceding-sibling::data/@section)]/@section
这将从数据元素中获取节属性,其中没有具有相同值的节属性的先前同级数据元素。
DOM 示例:
$dom = new DOMDocument();
$dom->load("file.xml");
$xpath = new DOMXPath($dom);
$query = '//data[not(@section = preceding-sibling::data/@section)]/@section';
foreach ($xpath->query($query) as $text) {
$sections[] = $text->value;
}
print_r($sections);
简单 XML 示例:
$xml = simplexml_load_file("file.xml");
$query = '//data[not(@section = preceding-sibling::data/@section)]/@section';
foreach ($xml->xpath($query) as $text) {
$sections[] = (string)$text;
}
print_r($sections);
以下任一内容的输出:
Array
(
[0] => Section 1
[1] => Section 2
[2] => Section 3
)