获取包含xml中某些字符串的子元素的所有根元素

时间:2012-03-17 17:38:36

标签: php xml

您好我试图从xml中仅返回某个元素..这样更容易解释:

<HotelList activePropertyCount="129" size="20">
<HotelSummary ubsScore="820" order="0">
<hotelId>121196</hotelId>
<name>ME Cancun - Complete ME All Inclusive</name>
<address1>Boulevard Kukulkan Km 12</address1>
<city>Cancun</city>
<postalCode>77500</postalCode>
<countryCode>MX</countryCode>
</HotelSummary>
</HotelList>

这些都有不同的hotelID。我需要获得具有<HotelSummary>子元素的<hotelID>121196</hotelID>。我无法弄清楚如何做到这一点。我正在使用PHP,这是我到目前为止所有:

<?
$post_string = 'type=xml&cid=55505&minorRev=13&apiKey=4sr8d8bsn75tpcuja6ypx5g3&locale=en_US&currencyCode=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=<HotelListRequest><arrivalDate>04/05/2012</arrivalDate><departureDate>04/07/2012</departureDate><RoomGroup><Room><numberOfAdults>2</numberOfAdults></Room><Room><numberOfAdults>2</numberOfAdults><numberOfChildren></numberOfChildren></Room></RoomGroup><city>Cancun</city><countryCode>MX</countryCode><supplierCacheTolerance>MED_ENHANCED</supplierCacheTolerance></HotelListRequest> ';
$path = "http://api.ean.com/ean-services/rs/hotel/v3/list"; //Relative path to the file with $_POST parsing
$ch = curl_init($path); 
$fp = fopen('room.xml','w');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); //Send the data to the file
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');

$info=$data->HotelList->HotelSummary->hotelId="123658";
$rating=$info->hotelRating;
echo $rating;
?>

提前谢谢!!!

1 个答案:

答案 0 :(得分:0)

循环查找特定ID。

foreach($data->HotelList->HotelSummary as $hotel) {
    if ($hotel->hotelId == 121196) {
        // This is it.
        break;
    }
}