I've been trying to figure out how to open an xml file and parse it as an array. But I can't seem to get it working properly. Here's the XML file:
<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>
Here's my php code (to pass it as an array):
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;
}
Which works, and gives me this array:
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
)
)
)
)
)
)
)
But when I try to run through the array and echo out the information, it fails. Here's the code I'm trying to use for that:
foreach($xmlArr->RMSAvailRateChartRS[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
};
But the error I'm getting is: Fatal error: Call to a member function attributes() on a non-object in default.php on line 33
Could someone please help me echoing out the details of the XML file?
var_dumpandprint_r, I suggest you to read through php.net/simplexml.examples-basic for generic usage of SimpleXML. For concrete questions about simplexml in PHP you can also search within the tag simplexml it has some good and common questions answered, most likely anything you'll ever need with it :)