我有一个XML结构,其中多个标签共享相同的名称,需要使用PHP处理它。
我正在使用SimpleXMLElement PHP类(http://php.net/manual/en/class.simplexmlelement.php)来实现这一目标。
我需要处理的XML的一个例子是:
<parent>
<child>
<attribute>
<name>hair</name>
<value>blond</value>
</attribute>
<attribute>
<name>height</name>
<value>1.2m</value>
</attribute>
<attribute>
<name>weight</name>
<value>35kg</value>
</attribute>
</child>
</parent>
然后我在PHP中使用类似的东西处理数据:
$data = get_data();
$xml = simplexml_load_string($data);
foreach($xml as $child) {
$hairColour = $child->Attribute[0]->value);
$height = $child->Attribute[1]->value);
$wegith = ($child->Attribute[2]->value);
// do stuff with data
}
问题是,我真的不愿意按顺序获取属性,因为未来可能会发生变化。我更倾向于通过他们的名字来获取属性,所以(我意识到这不起作用,但它是我正在努力实现的一个很好的例子):
$data = get_data();
$xml = simplexml_load_string($data);
foreach($xml as $child) {
$hairColour = $child->Attribute('hair')->value);
$height = $child->Attribute('height')->value);
$wegith = ($child->Attribute('weight)->value);
// do stuff with data
}
这实际上可行吗?我似乎无法在与此相关的文档中找到任何内容。
答案 0 :(得分:1)
使用XPath可以做到
//attribute/name[text()='hair']/following-sibling::value[1]
在你的情况下可能看起来像:
$xml = simplexml_load_string(get_data());
var_dump($xml->xpath("//attribute/name[text()='hair']/following-sibling::value[1]"));
如果你把它放到一个功能中,你几乎就在那里。