是否可以从以下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
)
答案 0 :(得分:0)
您正在寻找获得独特结果的xpath表达式:
//data[not(@section = preceding-sibling::data/@section)]/@section
这可以从数据元素中获取部分属性,其中没有先前的兄弟数据元素,其中部分属性具有相同的值。
$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 = 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
)