您正在尝试访问包含attribute =某个值的元素。我使用的是Expedia API,但我无法使用它。以下是我连接xml文件的方法:
$ch = curl_init();
$fp = fopen('room.xml','w');
curl_setopt($ch, CURLOPT_URL, "http://api.ean.com/ean-services/rs/hotel/v3/info?cid=55505&minorRev=13&apiKey=4sr8d8bsn75tpcuja6ypx5g3&locale=en_US¤cyCode=USD&customerIpAddress=10.184.2.9&customerUserAgent=Mozilla/5.0+(Windows+NT+6.1)+AppleWebKit/535.11+(KHTML,+like+Gecko)+Chrome/17.0.963.79+Safari/535.11&customerSessionId=&xml=<HotelInformationRequest><hotelId>".$hid."</hotelId><options>0</options></HotelInformationRequest>");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/xml'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FILE, $fp);
$val = curl_exec($ch);
curl_close($ch);//Close curl session
fclose($fp); //Close file overwrite
$data = simplexml_load_file('room.xml');
然后这是xml响应的一个例子:
<ns2:HotelInformationResponse xmlns:ns2="http://v3.hotel.wsapi.ean.com/" hotelId="121196">
<customerSessionId>0ABAA871-3187-D691-3682-CC27421918AC</customerSessionId>
<HotelSummary order="0">...</HotelSummary>
<HotelDetails>...</HotelDetails>
<Suppliers size="2">...</Suppliers>
<RoomTypes size="9">
<RoomType roomCode="17918" roomTypeId="136767">
<description>Deluxe Sunset View</description>
<descriptionLong>
One king or two double beds. 38.5 meters (414 square feet). Floors 1–9. Complimentary wireless Internet access. CD/DVD player. MP3 docking station. Complimentary newspapers. Minibar. Coffeemaker. Bathroom with shower only. Aveda toiletries. Bathrobes. Bathroom scale. Laptop-compatible safe. Turndown service.
</descriptionLong>
</RoomType>
</RoomTypes>
最后,这是我试图访问它的方式:
<?php $dataroom = $data->RoomTypes->RoomType['@roomCode="17918"']->description; var_dump($dataroom); ?>
正如您所看到的,我正在尝试访问roomCode = 17918的描述。但它无法正常工作!!我尝试使用回声和打印,没有任何作用。 var_dump返回NULL值。我不知道我做错了什么。我可以得到我想要的任何其他元素,但不是我需要匹配的地方。
答案 0 :(得分:0)
试试这个:
$dataroom = get_object_vars($data->RoomTypes->RoomType);
if($dataroom['@attributes']['roomCode'] == 17918) echo $dataroom['description'];
当然你必须相应地添加额外的循环,但是这应该可以正常工作,我只使用在线代码执行工具测试它并且似乎有效。
您尝试的方法并不是特别正确。您正尝试将对象作为数组访问。我正在将对象转换为数组,然后我将其作为数组访问。
答案 1 :(得分:0)
我想出来了......谢谢大家的帮助..绝对帮助我朝着正确的方向前进!以下是我如何解决它:
foreach($data->RoomTypes->RoomType AS $match){
if($match['roomCode']== "$roomCode"){
echo $match->descriptionLong;
}}