从肥皂反应中提取某些元素

时间:2014-09-01 12:02:41

标签: php web-services soap soap-client

我生命中第一次尝试将wsdl服务实现到网站中。我得到了服务的回复。我尝试使用以下代码解析响应,但可能在某处做错了。任何人都可以帮我解析响应中的某些节点吗?

问候并致谢

$xml = simplexml_load_string($result);


$hotels = $xml->children('http://schemas.xmlsoap.org/soap/envelope')->Body->children('http://axis.frontend.hydra.hotelbeds.com')->hoteldetailrs->hotel;

foreach ($hotels as $hotel) {
    echo ' 

        <hoteldetails>
            <h1>' .$hotel->name . '</h1>
            <h2>' .$hotel->code . '</h2>
        </hoteldetails>

     ';
}

肥皂反应

  <!--?xml version="1.0" encoding="utf-8"?-->
<soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:body>
    <ns1:gethoteldetail xsi:type="xsd:string" xmlns:ns1="http://axis.frontend.hydra.hotelbeds.com">
      <hoteldetailrs xmlns="http://www.hotelbeds.com/schemas/2005/06/messages" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://www.hotelbeds.com/schemas/2005/06/messages HotelDetailRS.xsd" echotoken="DummyEchoToken">
        <auditdata>
          <processtime>7</processtime>
          <timestamp>2014-09-01 13:39:27.027</timestamp>
          <requesthost>78.135.9.124</requesthost>
          <servername>FORM</servername>
          <serverid>FO</serverid>
          <schemarelease>2005/06</schemarelease>
          <hydracorerelease>2.0.201408281727</hydracorerelease>
          <hydraenumerationsrelease>1.0.201408281727</hydraenumerationsrelease>
          <merlinrelease>N/A</merlinrelease>
        </auditdata>
        <hotel xsi:type="ProductHotel">
          <code>50</code>
          <name>Aquahotel Aquamarina</name>
          <descriptionlist>
            <description type="HotelDescription" languagecode="ENG" languagename="Ingles">This attractive beach hotel is located on the sea front promenade of Santa Susanna, only 100 m from the beach. In the vicinity there are shops, bars, restaurants and night clubs. Girona Airport is 30 km away, Airport Barcelona-El Prat 60 km. The centre of Barcelona can be reached by train, calling at Plaça Catalunya. The hotel features 601 rooms, 24-hours reception, currency exchange, conference facilities, TV room, restaurant, 4 bars, outdoor pool, children's pool, playground, mini-club, cinema, supermarket and hairdresser. Facilities for disabled guests.</description>
          </descriptionlist>

          <contact>
            <address>
              <streettypeid>.</streettypeid>
              <streettypename> </streettypename>
              <streetname>AVENIDA DEL MAR</streetname>
              <number>16</number>
              <postalcode> 08398</postalcode>
              <city>SANTA SUSANA</city>
              <countrycode>ES</countrycode>
            </address>
            <emaillist>
              <email>aquahotel@aquahotel.com</email>
            </emaillist>
            <phonelist>
              <contactnumber type="phoneHotel">937678060</contactnumber>
              <contactnumber type="phoneBooking">902206306</contactnumber>
            </phonelist>
            <faxlist>
              <contactnumber>937678137</contactnumber>
            </faxlist>
            <weblist>
              <web>www.aquahotel.com</web>
            </weblist>
          </contact>
          <category type="SIMPLE" code="4EST" shortname="4*">4 STARS</category>
          <destination type="SIMPLE" code="LLM">
            <name>Costa Brava &amp; Costa Barcelona-Maresme</name>
            <zonelist>
              <zone type="SIMPLE" code="15">Santa Susana</zone>
            </zonelist>
          </destination>   
          <position latitude="41.63434" longitude="2.72169"></position>
        </hotel>
      </hoteldetailrs>
    </ns1:gethoteldetail>
  </soapenv:body>
</soapenv:envelope>

4 个答案:

答案 0 :(得分:3)

您没有正确定位名称空间。如果您遇到困难,请使用getNamespaces查看如何处理它们,并且很容易定位所需的节点:

$namespaces = $xml->getNamespaces(true);

$hotels = $xml->children($namespaces['soapenv'])
              ->body
              ->children($namespaces['ns1'])
              ->children()
              ->hoteldetailrs
              ->hotel;

foreach ($hotels as $hotel) {
    echo ' 
        <hoteldetails>
            <h1>' .$hotel->name . '</h1>
            <h2>' .$hotel->code . '</h2>
        </hoteldetails>
     ';
}

输出:

Aquahotel Aquamarina

50

如果您需要在children()上使用作为参数指定的命名空间的更多解释,请告诉我,但请务必先查看children()的文档

答案 1 :(得分:2)

要简化这些元素,您可以非常轻松地使用DOM

示例1:

$dom = new DOMDocument();
$dom->loadXML($result);
$hotels = $dom->getElementsByTagName('hotel');

foreach ($hotels as $hotel) {
    $name = $hotel->getElementsByTagName('name')->item(0)->nodeValue;
    $code = $hotel->getElementsByTagName('code')->item(0)->nodeValue;
    echo '

        <hoteldetails>
            <h1>' .$name . '</h1>
            <h2>' .$code . '</h2>
        </hoteldetails>

     ';
}

输出1:

<hoteldetails>
    <h1>Aquahotel Aquamarina</h1>
    <h2>50</h2>
</hoteldetails>

虽然我不是通过字符串连接创建输出XML的忠实粉丝。另一种方法是建立另一个DOM并输出它。它只是更冗长,但最终更清洁。

示例2:

$dom = new DOMDocument();
$dom->loadXML($result);
$hotels = $dom->getElementsByTagName('hotel');

foreach ($hotels as $hotel) {
    // Get the data for each hotel.
    $name = $hotel->getElementsByTagName('name')->item(0)->nodeValue;
    $code = $hotel->getElementsByTagName('code')->item(0)->nodeValue;

    // Set up a DOM to hold everything.
    $output = new DOMDocument();
    $output->formatOutput = true;

    // Create some elements.
    $hoteldetails = $output->createElement('hoteldetails');
    $h1           = $output->createElement('h1', $name);
    $h2           = $output->createElement('h2', $code);

    // Put them together.
    $hoteldetails->appendChild($h1);
    $hoteldetails->appendChild($h2);

    echo $output->saveXML($hoteldetails);
}

输出2:

<hoteldetails>
  <h1>Aquahotel Aquamarina</h1>
  <h2>50</h2>
</hoteldetails>

答案 2 :(得分:1)

$client = new SoapClient("http://path.to/wsdl?WSDL");
$res = $client->SoapFunction(array('param1'=>'value','param2'=>'value'));
echo $res->gethoteldetail->city;

答案 3 :(得分:0)

您可以使用以下函数来解析xml数据:

$str = '<!--?xml version="1.0" encoding="utf-8"?--> ..... ';
$ResponseData = xml2array($str, 0); 
$HotelData = $ResponseData['soapenv:envelope']['soapenv:body']['ns1:gethoteldetail']['hoteldetailrs'];
echo "<pre>"; print_r($HotelData); die;

功能:

function xml2array($contents, $get_attributes=1, $priority = 'tag') {

    if(!$contents) return array();

    if(!function_exists('xml_parser_create')) {
        return array();
    }

    $parser = xml_parser_create('');
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); 
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);

    if(!$xml_values) return;

    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();
    $current = &$xml_array;
    $repeated_tag_index = array();

    foreach($xml_values as $data) {

        unset($attributes,$value);
        extract($data);

        $result = array();
        $attributes_data = array();

        if(isset($value)) {         
            if($priority == 'tag')  $result = $value;  else  $result['value'] = $value;
        }   
        if(isset($attributes) and $get_attributes) {            
            foreach($attributes as $attr => $val) {             
                if($priority == 'tag') 
                    $attributes_data[$attr] = $val;
                else 
                    $result['attr'][$attr] = $val;
            }
        }       
        if($type == "open") {       
            $parent[$level-1] = &$current;          
            if(!is_array($current) or (!in_array($tag, array_keys($current)))) {            
                $current[$tag] = $result;               
                if($attributes_data) $current[$tag. '_attr'] = $attributes_data;                
                $repeated_tag_index[$tag.'_'.$level] = 1;
                $current = &$current[$tag];             
            } else {            
                if(isset($current[$tag][0])) {              
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    $repeated_tag_index[$tag.'_'.$level]++;                 
                } else {                
                    $current[$tag] = array($current[$tag],$result);
                    $repeated_tag_index[$tag.'_'.$level] = 2;                   
                    if(isset($current[$tag.'_attr'])) {                 
                        $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                        unset($current[$tag.'_attr']);
                    }
                }               
                $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
                $current = &$current[$tag][$last_item_index];
            }

        } elseif($type == "complete") { 
            if(!isset($current[$tag])) {            
                $current[$tag] = $result;
                $repeated_tag_index[$tag.'_'.$level] = 1;
                if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;             
            } else {            
                if(isset($current[$tag][0]) and is_array($current[$tag])) {                 
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    if($priority == 'tag' and $get_attributes and $attributes_data) {
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag.'_'.$level]++;                 
                } else {                
                    $current[$tag] = array($current[$tag],$result); 
                    $repeated_tag_index[$tag.'_'.$level] = 1;
                    if($priority == 'tag' and $get_attributes) {
                        if(isset($current[$tag.'_attr'])) { 
                            $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                            unset($current[$tag.'_attr']);
                        }
                        if($attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag.'_'.$level]++; 
                }
            }           
        } elseif($type == 'close') { 
            $current = &$parent[$level-1];
        }
    }

    return($xml_array);
}

我希望这会对你有所帮助。