【发布时间】:2013-10-31 03:15:14
【问题描述】:
我一直在试图弄清楚如何打开一个 xml 文件并将其解析为一个数组。但我似乎无法让它正常工作。这是 XML 文件:
<RMSAvailRateChartRS Version="1.0.0.0">
<SoldMessage>call</SoldMessage>
<RoomTypes>
<RoomType>
<RoomTypeId>10</RoomTypeId>
<SubPropertyId>1</SubPropertyId>
<Name>K</Name>
<MaxOccupancy>2</MaxOccupancy>
<Availability Id="1" Date="2013-11-04" Available="false" NoOfRoomsAvailable="0" />
<BookingRangeAvailable>false</BookingRangeAvailable>
<ChargeTypes>
<ChargeType>
<ChargeTypeId>8</ChargeTypeId>
<Name>BAR</Name>
<Description>Best Rate Available</Description>
<Charge Id="1" Date="2013-11-04" Price="100.00" MinStay="1" MaxStay="25" ValidCharge="true" IncludeChildInBase="false" IncludeInfantInBase="false" Flames="false" CanArriveToday="True" PersonBase="2" ChildBase="0" InfantBase="0" />
</ChargeType>
</ChargeTypes>
</RoomType>
</RoomTypes>
</RMSAvailRateChartRS>
这是我的 php 代码(将其作为数组传递):
public static function getXML($id) {
$file = JPATH_SITE.'/tmp/request-'.$id.'.xml';
if (file_exists($file)) :
$xml = simplexml_load_file($file,'SimpleXMLElement',LIBXML_NOCDATA);
return $xml;
else :
exit('Failed to open '.$file.'.');
endif;
}
哪个有效,并给了我这个数组:
SimpleXMLElement Object
(
[@attributes] => Array
(
[Version] => 1.0.0.0
)
[SoldMessage] => call
[RoomTypes] => SimpleXMLElement Object
(
[RoomType] => SimpleXMLElement Object
(
[RoomTypeId] => 10
[SubPropertyId] => 1
[Name] => K
[MaxOccupancy] => 2
[Availability] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Id] => 1
[Date] => 2013-11-04
[Available] => false
[NoOfRoomsAvailable] => 0
)
)
[BookingRangeAvailable] => false
[ChargeTypes] => SimpleXMLElement Object
(
[ChargeType] => SimpleXMLElement Object
(
[ChargeTypeId] => 8
[Name] => BAR
[Description] => Best Rate Available
[Charge] => SimpleXMLElement Object
(
[@attributes] => Array
(
[Id] => 1
[Date] => 2013-11-04
[Price] => 100.00
[MinStay] => 1
[MaxStay] => 25
[ValidCharge] => true
[IncludeChildInBase] => false
[IncludeInfantInBase] => false
[Flames] => false
[CanArriveToday] => True
[PersonBase] => 2
[ChildBase] => 0
[InfantBase] => 0
)
)
)
)
)
)
)
但是当我尝试遍历数组并回显信息时,它失败了。这是我尝试使用的代码:
foreach($xmlArr->RMSAvailRateChartRS[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
};
但我得到的错误是:致命错误:在第 33 行的 default.php 中调用非对象的成员函数 attributes()
有人可以帮我把 XML 文件的详细信息重复一遍吗?
【问题讨论】:
-
它不是一个数组,它是一个对象。 SimpleXML 在这里与
var_dump和print_r有点误导,我建议您通读php.net/simplexml.examples-basic 以了解SimpleXML 的一般用法。对于 PHP 中有关 simplexml 的具体问题,您还可以在标签 simplexml 中进行搜索,它回答了一些很好且常见的问题,很可能是您需要的任何问题 :)
标签: php xml arrays xml-parsing simplexml