SimpleXML部分元素属性未显示问题及访问方法咨询
问题描述
我有一份外部XML文件内容如下:
<?xml version="1.0" encoding="UTF-8"?> <propertyList date="2024-08-27-10:09:55"> <residential modTime="2024-08-27-10:01:59" status="current"> <uniqueID>1P0100</uniqueID> <authority value="auction"/> <price display="yes">6000000</price> <landDetails> <area unit="hectare">5.09</area> <frontage unit="meter">0</frontage> </landDetails> <address display="yes" streetview="yes"> <streetNumber>123</streetNumber> <street>Smith St</street> <suburb display="yes">My Suburb</suburb> <state>My State</state> <postcode>1234</postcode> </address> <category name="House"/> </residential> </propertyList>
使用以下PHP代码调用simplexml_load_file:
$xml = simplexml_load_file("properties.xml"); $residential = $xml->residential; print_r($residential);
输出的对象如下:
SimpleXMLElement Object ( [@attributes] => Array ( [modTime] => 2024-08-27-10:01:59 [status] => current ) [uniqueID] => 1P0100 [authority] => SimpleXMLElement Object ( [@attributes] => Array ( [value] => auction ) ) [price] => 6000000 [landDetails] => SimpleXMLElement Object ( [area] => 5.09 [frontage] => 0 ) [address] => SimpleXMLElement Object ( [@attributes] => Array ( [display] => yes [streetview] => yes ) [streetNumber] => 123 [street] => Smith St [suburb] => My Suburb [state] => My State [postcode] => 1234 ) [category] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => House ) ) )
可以看到,price、landDetails->area和landDetails->frontage元素的属性未在SimpleXMLElement对象中返回,其他元素的属性则正常返回。请问为何这些属性未被包含,以及如何访问它们?
问题解答
一、属性未在print_r中显示的原因
SimpleXMLElement是PHP中专门处理XML的魔术对象,它的内部结构不会被print_r或var_dump完全暴露。当元素同时包含文本内容和属性时,print_r会默认优先展示文本内容,隐藏属性——但这并不代表属性不存在,只是输出时未被展示而已。
比如price元素既有文本值6000000,又有display="yes"属性;area元素既有文本值5.09,又有unit="hectare"属性,这类元素的属性就不会在print_r的输出里直接显示。而像authority、category这类没有文本内容、仅含属性的元素,print_r才会显示它们的属性数组。
二、访问这些属性的方法
SimpleXMLElement提供了两种标准方式来访问元素属性:
1. 数组下标语法
直接通过['属性名']的形式获取目标属性:
// 获取price的display属性 $priceDisplay = $residential->price['display']; echo $priceDisplay; // 输出yes // 获取area的unit属性 $areaUnit = $residential->landDetails->area['unit']; echo $areaUnit; // 输出hectare // 获取frontage的unit属性 $frontageUnit = $residential->landDetails->frontage['unit']; echo $frontageUnit; // 输出meter
2. attributes()方法
调用元素的attributes()方法可以获取该元素的所有属性集合(返回SimpleXMLElement对象),再通过下标访问具体属性:
// 获取price的所有属性 $priceAttrs = $residential->price->attributes(); echo $priceAttrs['display']; // 输出yes // 获取area的所有属性 $areaAttrs = $residential->landDetails->area->attributes(); echo $areaAttrs['unit']; // 输出hectare
如果需要同时获取元素的文本内容和属性,直接访问元素本身即可得到文本值,再用上述方法获取属性:
$priceValue = (string)$residential->price; // 输出6000000 $priceDisplay = $residential->price['display']; // 输出yes
内容的提问来源于stack exchange,提问作者user606336
相关产品推荐
相关产品推荐

