可能重复:
A simple program to CRUD node and node values of xml file
如何从此XML Feed中获取特定属性?
示例 - 我一直在使用与此类似的行来获取其他XML详细信息,但我不确定如何更改它以获取特定属性。
$mainPropertyDetails = $mainPropertyUrl->Attributes->attribute;
属性:
<Attributes>
<Attribute>
<Name>bedrooms</Name>
<DisplayName>Bedrooms</DisplayName>
<Value>4 bedrooms</Value>
</Attribute>
<Attribute>
<Name>bathrooms</Name>
<DisplayName>Bathrooms</DisplayName>
<Value>2 bathrooms</Value>
</Attribute>
<Attribute>
<Name>property_type</Name>
<DisplayName>Property type</DisplayName>
<Value>House</Value>
</Attribute>
答案 0 :(得分:1)
SimpleXML
将这些节点实现为数组。如果你要var_dump()
这个,你会看到类似的东西:
// Dump the whole Attributes array
php > var_dump($xml->Attributes);
object(SimpleXMLElement)#6 (1) {
["Attribute"]=>
array(3) {
[0]=>
object(SimpleXMLElement)#2 (3) {
["Name"]=>
string(8) "bedrooms"
["DisplayName"]=>
string(8) "Bedrooms"
["Value"]=>
string(10) "4 bedrooms"
}
[1]=>
object(SimpleXMLElement)#5 (3) {
["Name"]=>
string(9) "bathrooms"
["DisplayName"]=>
string(9) "Bathrooms"
["Value"]=>
string(11) "2 bathrooms"
}
[2]=>
object(SimpleXMLElement)#3 (3) {
["Name"]=>
string(13) "property_type"
["DisplayName"]=>
string(13) "Property type"
["Value"]=>
string(5) "House"
}
}
}
因此,只需通过数组索引访问特定的那些:
// Get the second Attribute node
var_dump($xml->Attributes[0]->Attribute[1]);
object(SimpleXMLElement)#6 (3) {
["Name"]=>
string(9) "bathrooms"
["DisplayName"]=>
string(9) "Bathrooms"
["Value"]=>
string(11) "2 bathrooms"
}
使用xpath()
,您可以根据子项的文本值查询父Attribute
节点:
// Get the Attribute containing the Bathrooms DisplayName
// Child's text value is queried via [AttrName/text()="value"]
var_dump($xml->xpath('//Attributes/Attribute[DisplayName/text()="Bathrooms"]');
array(1) {
[0]=>
object(SimpleXMLElement)#6 (3) {
["Name"]=>
string(9) "bathrooms"
["DisplayName"]=>
string(9) "Bathrooms"
["Value"]=>
string(11) "2 bathrooms"
}
}