2013-06-11 3 views
0

Я создаю фид продукта, и у меня возникают некоторые проблемы с извлечением значения xml, которое лежит глубоко в коде xml.Как извлечь значение xml, которое находится глубоко в xml-коде

XML-код является: (на этот вопрос я очистил несоответствующие значения)

<ns2:HotelListResponse xmlns:ns2="http://v3.hotel.wsapi.ean.com/"> 
    <customerSessionId>0ABAAA78-D672-ED91-3F32-332C20D917D9</customerSessionId> 
    <numberOfRoomsRequested>1</numberOfRoomsRequested> 
    <moreResultsAvailable>true</moreResultsAvailable> 
    <cacheKey>-39d672ed:13f3332c20d:1b00</cacheKey> 
    <cacheLocation>10.186.170.120:7300</cacheLocation> 
    <HotelList activePropertyCount="1621" size="1"> 
     <HotelSummary order="0"> 
      <RoomRateDetailsList> 
        <RoomRateDetails>  
         <RateInfo rateChange="true" promo="true" priceBreakdown="true"> 
           <ChargeableRateInfo total="656.27" surchargeTotal="42.94"   nightlyRateTotal="613.32996" maxNightlyRate="178.42" currencyCode="USD" commissionableUsdTotal="613.32996" averageRate="153.33249" averageBaseRate="170.37251"> 
         </RateInfo> 
       </RoomRateDetails> 
      </RoomRateDetailsList> 
     </HotelSummary> 
    </HotelList> 
    </ns2:HotelListResponse> 

РНР код я использую:

<?php 
    $post_string ='type=xml'; 
    $post_string .= '&cid=55505'; 
    $post_string .= '&minorRev=24'; 
    $post_string .= '&apiKey=wwfzhd95v9vtzh4jc8yjcug9'; 
    $post_string .= '&locale=nl_NL'; 
    $post_string .= '&currencyCode=EUR'; 
    $post_string .= '&customerIpAddress=10.184.2.9'; 
    $post_string .= '&customerUserAgent=Mozilla/5.0+(Windows+NT+6.1)+AppleWebKit  /535.11+(KHTML,+like+Gecko)+Chrome/17.0.963.79+Safari  /535.11'; 
    $post_string .= '&customerSessionId='; 
    $post_string .= '&xml='; 
    $post_string .= '<HotelListRequest>'; 
    $post_string .= '<arrivalDate>$checkindate</arrivalDate>'; 
    $post_string .= '<departureDate>$checkoutdate</departureDate>'; 
    $post_string .= '<RoomGroup>'; 
    $post_string .= '<Room>'; 
    $post_string .= '<numberOfAdults>2</numberOfAdults>'; 
    $post_string .= '</Room>'; 
    $post_string .= '<Room>'; 
    $post_string .= '<numberOfAdults>$adultcount</numberOfAdults>'; 
    $post_string .= '<numberOfChildren></numberOfChildren>'; 
    $post_string .= '</Room>'; 
    $post_string .= '</RoomGroup>'; 
    $post_string .= '<latitude>'; 
    $post_string .= $lat; 
    $post_string .= '</latitude>'; 
    $post_string .= '<longitude>'; 
    $post_string .= $long; 
    $post_string .= '</longitude>'; 
    $post_string .= '<searchRadius>30</searchRadius>'; 
    $post_string .= '<searchRadiusUnit>km</searchRadiusUnit>'; 
    $post_string .= '<minStarRating>'; 
    $post_string .= $ratingmin; 
    $post_string .= '</minStarRating>'; 
    $post_string .= '<maxStarRating>'; 
    $post_string .= $ratingmax; 
    $post_string .= '</maxStarRating>'; 
    $post_string .= '<minRate>'; 
    $post_string .= $minprice; 
    $post_string .= '</minRate>'; 
    $post_string .= '<maxRate>'; 
    $post_string .= $maxprice; 
    $post_string .= '</maxRate>'; 
    $post_string .= '<tripAdvisorRatingUrl>'; 
    $post_string .= $mintripadvisorarray; 
    $post_string .= '</tripAdvisorRatingUrl>'; 
    $post_string .= '<countryCode>FR</countryCode>'; 
    $post_string .= '<supplierCacheTolerance>MED_ENHANCED</supplierCacheTolerance>'; 
    $post_string .= '<sort>'; 
    $post_string .= $sort; 
    $post_string .= '</sort>'; 
    $post_string .= '<numberOfResults>10</numberOfResults>'; 
    $post_string .= '</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('data.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 

    //Use Curl to get XML here. 

    $data = simplexml_load_file('data.xml'); 

    //Uncomment this to view the parsed XML on screen. 
    /* 
    echo '<pre>'; 
    print_r($data->HotelList); 
    echo '</pre>'; 
    */ 

    echo "<ul id=\"data\">\n"; 
    $resultnumber = 0; 
    foreach($data->HotelList->HotelSummary as $info): 

$resultnumber++; 
$title=$info->name; 
$add=$info->address1; 
$city=$info->city; 
$locationdescription=$info->locationDescription; 
$locationdescription = lcfirst($locationdescription); 
$count=$data->HotelList['activePropertyCount']; 
$thumbnail1=$info->thumbNailUrl; 
$thumbnail2= "http://images.travelnow.com"; 
$thumbnail = $thumbnail2.$thumbnail1; 
$image = substr_replace($thumbnail, 'l', -5, -4); 
$image1 = substr_replace($thumbnail, 'n', -5, -4); 
$image2 = substr_replace($thumbnail, 'g', -5, -4); 
$image3 = substr_replace($thumbnail, 'd', -5, -4); 
$image4 = substr_replace($thumbnail, 'y', -5, -4); 
$image5 = substr_replace($thumbnail, 'z', -5, -4); 
$chargerate= $data->RoomRateDetailsList->RoomRateDetails->RateInfo->ChargeableRateInfo['total']; 
$highrate=$info->highRate; 
$prijs= round($highrate,0); 
$deeplink=$info->deepLink; 
$hotelrating=$info->hotelRating; 
$hotelratinground = round($hotelrating,0); 
$tripadvisorratingurl=$info->tripAdvisorRatingUrl; 
$distance =$info->proximityDistance; 
$distanceround= round($distance,0); 
$chargeableRateInfo = $rateInfo->ChargeableRateInfo['total']; 

echo 
    "<li> 
     <time> <i>Hotel ",$resultnumber," van ",$count,"</i> </time>       
     <div class=\"title\"><b> ",$title," <img src='../pics/",$hotelratinground,"-star-rating.png' width='100' height='20'></b></div> 
     <div class=\"artist\">Adres: ",$add,"</div> 
     <div class=\"locatie\">Locatie: ",$city,", ",$locationdescription,"</div> 
     <div class=\"image\"><img src=$image /></div> 
     <div class=\"prijs\">Prijs: €",$chargerate,"</div> 
     <div class=\"deeplink\"><a href=",$deeplink,">Bekijk aanbieding</a></div> 
     <div class=\"hotelrating\"> ",$hotelrating," sterren</div> 
     <div class=\"tripadvisorratingurl\"><img src=$tripadvisorratingurl/> ",$tripadvisorratingurl," </div> 
     <div class=\"distance \"> Afstand: ",$distanceround," km </div><br>      
    </li>\n"; 

    endforeach; 

    echo "</ul>"; 


    ?> 

Весь код работает нормально и делать, как предполагается, делать. Execpt линия:

$chargerate= $data->RoomRateDetailsList->RoomRateDetails->RateInfo->ChargeableRateInfo['total']; 

Может кто-нибудь объяснить мне, что я делаю неправильно?

+0

Первое, что вы можете сделать неправильно, это не искать ошибки, см.: [Как получить полезные сообщения об ошибках в PHP?] (Http://stackoverflow.com/a/14504459/367456). Следующее, что вы можете сделать неправильно, - это не смотреть на существующий материал, который обычно объясняет, как делаются, показывает альтернативные способы и предоставляет рабочие примеры. См. [Основное использование SimpleXML] (http://php.net/simplexml.examples-basic) и многие другие и связанные с ними вопросы здесь о stackoverflow. – hakre

ответ

1

Вместо

$chargerate= $data->RoomRateDetailsList->RoomRateDetails->RateInfo->ChargeableRateInfo['total']; 

использования

$chargerate= $info->RoomRateDetailsList->RoomRateDetails->RateInfo->ChargeableRateInfo['total']; 
      ^^^^^ 

$data содержит полный ответ в то время как Вы должны быть в пределах конкретного $data->HotelList->HotelSummary, который находится в $info из цикла foreach().

Также линия

$chargeableRateInfo = $rateInfo->ChargeableRateInfo['total']; 

выглядит подозрительно, как переменная $rateinfo не установлен в любом месте, и он должен обратиться к $info->RoomRateDetailsList->RoomRateDetails->RateInfo ...

+0

Спасибо за реакцию. – user2474689

+0

Строка «$ chargeableRateInfo = $ rateInfo-> ChargeableRateInfo ['total'];" была пробной линией, действительно без ссылки в $ rateinfo. Я удалил его – user2474689

+0

Я попытался заменить $ data на $ info. К сожалению, это не сработало. – user2474689

0

Полный код XML:

<ns2:HotelListResponse xmlns:ns2="http://v3.hotel.wsapi.ean.com/"> 
<customerSessionId>0ABAAA88-25AD-1A91-3F32-88C0FB6909EC</customerSessionId> 
<numberOfRoomsRequested>1</numberOfRoomsRequested> 
<moreResultsAvailable>true</moreResultsAvailable> 
<cacheKey>-5825ad1a:13f388c0fb6:-7b1</cacheKey> 
<cacheLocation>10.186.170.136:7300</cacheLocation> 
<HotelList activePropertyCount="1620" size="1"> 
<HotelSummary order="0"> 
<hotelId>391066</hotelId> 
<name>Hotel Paradis</name> 
<address1>41 Rue Des Petites Ecuries</address1> 
<city>Paris</city> 
<postalCode>75010</postalCode> 
<countryCode>FR</countryCode> 
<airportCode>BVA</airportCode> 
<supplierType>E</supplierType> 
<propertyCategory>1</propertyCategory> 
<hotelRating>3.0</hotelRating> 
<confidenceRating>96</confidenceRating> 
<amenityMask>0</amenityMask> 
<tripAdvisorRating>2.0</tripAdvisorRating> 
<locationDescription>In Gare du Nord - Gare de l&apos;Est in Parijs</locationDescription> 
<shortDescription>&lt;p&gt;&lt;b&gt;Ligging.&lt;/b&gt; &lt;br /&gt;Hotel Paradis bevindt zich in Gare du Nord - Gare de l&apos;Est in Parijs, dicht bij Folies Bergères, Musée du Louvre en Notre-Dame van Parijs. Andere bezienswaardigheden in de</shortDescription> 
<highRate>199.12</highRate> 
<lowRate>145.6</lowRate> 
<rateCurrencyCode>USD</rateCurrencyCode> 
<latitude>48.8739</latitude> 
<longitude>2.34994</longitude> 
<proximityDistance>3.2130618</proximityDistance> 
<proximityUnit>MI</proximityUnit> 
<hotelInDestination>true</hotelInDestination> 
<thumbNailUrl>/hotels/1000000/10000/6200/6147/6147_43_t.jpg</thumbNailUrl> 
<deepLink>http://travel.ian.com/index.jsp?pageName=hotAvail&amp;cid=55505&amp;hotelID=391066&amp;mode=2&amp;numberOfRooms=1&amp;room-0-adult-total=2&amp;room-0-child-total=0&amp;arrivalMonth=6&amp;arrivalDay=8&amp;departureMonth=6&amp;departureDay=12&amp;showInfo=true&amp;locale=nl_NL</deepLink> 
<RoomRateDetailsList> 
<RoomRateDetails> 
<roomTypeCode>200103873</roomTypeCode> 
<rateCode>201121699</rateCode> 
<maxRoomOccupancy>2</maxRoomOccupancy> 
<quotedRoomOccupancy>2</quotedRoomOccupancy> 
<minGuestAge>0</minGuestAge> 
<roomDescription>Standaard, lits-jumeaux - Non Refundable</roomDescription> 
<promoId>202564842</promoId> 
<promoDescription>10% korting op dit verblijf!</promoDescription> 
<currentAllotment>1</currentAllotment> 
<propertyAvailable>true</propertyAvailable> 
<propertyRestricted>false</propertyRestricted> 
<expediaPropertyId>6147</expediaPropertyId> 
<rateKey>0ABAAA88-25AD-1A91-3F32-88C0FB6907B0</rateKey> 
<RateInfo rateChange="true" promo="true" priceBreakdown="true"> 
<ChargeableRateInfo total="659.12" surchargeTotal="43.11" nightlyRateTotal="616.01" maxNightlyRate="179.21" currencyCode="USD" commissionableUsdTotal="616.01" averageRate="154.0025" averageBaseRate="171.11499"> 
<NightlyRatesPerRoom size="4"> 
<NightlyRate promo="true" rate="145.6" baseRate="161.78"></NightlyRate> 
<NightlyRate promo="true" rate="145.6" baseRate="161.78"></NightlyRate> 
<NightlyRate promo="true" rate="179.21" baseRate="199.12"></NightlyRate> 
<NightlyRate promo="true" rate="145.6" baseRate="161.78"></NightlyRate> 
</NightlyRatesPerRoom> 
<Surcharges size="1"> 
<Surcharge amount="43.11" type="TaxAndServiceFee"></Surcharge> 
</Surcharges> 
</ChargeableRateInfo> 
</RateInfo> 
<ValueAdds size="1"> 
<ValueAdd id="2048"> 
<description>Gratis draadloos internet</description> 
</ValueAdd> 
</ValueAdds> 
</RoomRateDetails> 
     </RoomRateDetailsList> 
     </HotelSummary> 
    </HotelList> 
</ns2:HotelListResponse> 

обновленная строка ошибки после ваших предыдущих комментариев:

$chargerate= $info->RoomRateDetailsList->RoomRateDetails->RateInfo->ChargeableRateInfo['total']; 
Смежные вопросы