使用file_get_contents将数据从XML提取到php


Extract data from XML with file_get_contents to php

我正在向API发送一个请求,该API以XML格式发送响应。

回复如下:

<ns2:HotelInformationResponse hotelId="263933">
<customerSessionId>0ABAAA85-112B-0914-9322-CA866D907EF8</customerSessionId>
<HotelSummary order="0">
<hotelId>263933</hotelId>
<name>Nova Platinum Hotel</name>
<address1>562 Moo 10 Pratamnak Road, Nongprue</address1>
<address2>Banglamung</address2>
<city>Pattaya</city>
<postalCode>20260</postalCode>
<countryCode>TH</countryCode>

如何获取这些数据,以便打印hotelId或name等单个值?

我试过这样:

$Geosearch = 'APICALLURLHERE';
$fileContents = file_get_contents($Geosearch);
$string_data = $fileContents;
$xml = simplexml_load_string($string_data);
$hotel_id = (string) $xml->hotelId;
$hotel_name = (string) $xml->name;
echo $hotel_id.' '.$hotel_name;

我也尝试过这个:

$xml = simplexml_load_file("APICALLURLHERE");
echo $xml->hotelId;
echo $xml->name; 

访问远程文件

fopen函数族(包括file_get_contents和simplexml_load_file)默认情况下不允许访问远程文件。这是一件非常好的事情,应该保持这种状态。

如果你想启用远程文件,你必须更改你的PHP配置。

http://php.net/manual/en/features.remote-files.php

allow_url_fopen = 1


XML文件中的错误

如果您的文件加载正在进行,但您仍然无法使XML正常工作,则可能存在损坏的XML文件。您可以使用以下代码段调试这些问题:

$doc = simplexml_load_string($xmlstr);
if (!$doc) {
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        echo display_xml_error($error, $xml);
    }
    libxml_clear_errors();
}

http://php.net/manual/de/function.libxml-get-errors.php