您好,我試圖訪問包含屬性=某個值的元素。我正在使用Expedia API,但無法使其工作。這裏是我如何連接到XML文件:在xml和php中獲取匹配某個值的元素的屬性
$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的值。我不知道我做錯了什麼。我可以得到我想要的任何其他元素,但不是我需要它匹配的地方。
也許你應該追加' - > data'到'description'的末尾? – 2012-04-07 21:35:56
不知道:(沒有工作。 – liveandream 2012-04-07 21:40:11