我正在尝试从提供HotelCode的php数组中提取ImageUrl
,Lat和Long:$hotelCode
我的 XML 文件如下所示:
<Hotels>
<Hotel>
<HotelCode>Code<HotelCode>
<Latitude>Lat</Latitude>
<Longitude>Long</Longitude>
<HotelImages>
<ImageURL>file.jpg</ImageURL>
<ImageURL>file2.jpg</ImageURL>
....
</HotelImages>
</Hotel>
....
</Hotels>
我的PHP代码是:
$xmlstring = file_get_contents($xmlurl);
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$hotels = json_decode($json,TRUE);
print_r($hotels) is:
Array (
[Hotel] => Array (
[0] => Array (
[HotelCode] => ES002A
[comment] => Array (
[0] => Array ( ) )
[Latitude] => 37.396792
[Longitude] => -5.992054
[HotelImages] => Array (
[ImageURL] => Array (
[0] => http://image.metglobal.com/hotelimages/ES002A/9405329_0x0.jpg
[1] => http://image.metglobal.com/hotelimages/ES002A/9405330_0x0.jpg
[2] => http://image.metglobal.com/hotelimages/ES002A/9405331_0x0.jpg
)
)
)
print_r($hotelCodes) is
Array ( [0] => ESG56G [1] => ES0Z10 )
我尝试了一些不同的方法,但没有一种奏效。
好吧,首先,你的xml中有一个错误。
<HotelCode>Code<HotelCode>
应该是:
<HotelCode>Code</HotelCode>
之后,您可以通过以下方式获取图像:
$hotels['Hotel']['HotelImages']['ImageURL'][0];
和
$hotels['Hotel']['HotelImages']['ImageURL'][0];
和拉长恭敬:
$hotels['Hotel']['Latitude'];
$hotels['Hotel']['Longitude'];
您可以使用 foreach 循环 [Hotel] 数组,并检查 [HotelCode] 元素是否等于您提供的元素,然后返回纬度和经度属性。
foreach ($hotels as $hotel) {
if($hotel['HotelCode'] == 'YourCode'){
echo $hotel['Latitude'];
echo $hotel['Longtitude'];
}
}
使用 array_keys
$hotelCodes = array_keys($hotels, "HotelCode");
这将返回带有键"HotelCode"的所有值。然后,您可以使用这些值循环数组。
foreach ($hotelCodes as $code)
{
$iUrls = $hotels[$code]['HotelImages']['ImageURL'];
foreach ($iUrls as $iUrl)
{
echo $iUrl;
}
echo $hotels[$code]['Latitude'];
echo $hotels[$code]['Longitude'];
}