Search code examples
phpxmlsimplexml

Parsing of a XML response


I am completely new to XML.

I have a URL which gives me a XML response. I am facing problems in parsing the response and showing only the details that I want. Currently the url is "https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3ESeattle%3C%2Fcity%3E%3CstateProvinceCode%3EWA%3C%2FstateProvinceCode%3E%3CcountryCode%3EUS%3C%2FcountryCode%3E%3CarrivalDate%3E%3C%2FarrivalDate%3E%3CdepartureDate%3E9%2F1%2F2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E"

and I am using the following code:

$feed = file_get_contents($url);
$items = simplexml_load_string($feed);
print_r($items);

and this was the error file_get_contents( https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3EAmsterdam%3C%2Fcity%3E%3CarrivalDate%3E08/30/2014%3C%2FarrivalDate%3E%3CdepartureDate%3E08/31/2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E1%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E): failed to open stream: Invalid argument

I have also tried using simplexml_load_file() and it's showing the same error.


Solution

  • file_get_contents on the URL is returning content of type json, that's why simple_xml_load_file cannot parse it. Use this

    $feed =  file_get_contents("https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3ESeattle%3C%2Fcity%3E%3CstateProvinceCode%3EWA%3C%2FstateProvinceCode%3E%3CcountryCode%3EUS%3C%2FcountryCode%3E%3CarrivalDate%3E%3C%2FarrivalDate%3E%3CdepartureDate%3E9%2F1%2F2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E");
    //echo $feed;
    
    $json = json_decode($feed);
    
    print_r($json);