如何将此 XML 请求转换为 php 中的数组?

2021-12-24 00:00:00 xml php soap

我是 SOAP 新手.我无法将此请求转换为数组.这个xml数组应该是字符串类型的.

Xml 请求:

<POS><来源><UniqueId Id="20000704abcde:105ABCDE"/></来源><AvailRequestSegments><AvailRequestSegment><StayDateRange End="2011-08-15" Start="2011-08-14"/><RoomStayCandidates><RoomStayCandidate Quantity="1"><GuestCounts><GuestCount AgeQualifyingCode="10" Count="1"/></GuestCounts></RoomStayCandidate></RoomStayCandidates><酒店搜索标准><标准><HotelRef Destination="东伦敦,南非" CityCode="" CountryCode="" HotelName="" MinHotelRating="1"/><SearchCurrency>EUR</SearchCurrency><AdditionalInfo Value="1"/><语言>EN</语言></标准></酒店搜索标准></AvailRequestSegment></AvailRequestSegments></OTA_HotelAvailRQ>

xml 响应:

<成功 ID="24064"/><属性><Property HotelCityCode="4162" HotelCode="6001287" HotelName="Amaryllis"><RelativePosition Direction="" Distance="0" DistanceUnitName=""/><客房住宿><房间住宿><费率计划><RatePlan RatePlanCode="12201993"/></RatePlans><房价><房价><费率><Rate EffectiveDate="2010-06-12" ExpireDate="2010-06-13"><Base Amount="76.00" CurrencyCode="EUR"/><RateDescription Adults="1" Availability="A" Children="0" RoomNum="1"><![CDATA[单人间]]></RateDescription></费率></费率></房价></RoomRates><膳食说明="自助餐 B'Fast (大陆)"/><EssentialInfo>这里是重要信息</EssentialInfo></RoomStay></RoomStays><促销/><附加信息><HotelStarDetail rating="2"/><酒店图片><HotelImage Type="卧室" URL="https://www.miki.co.uk/live/hotel/mikiNet/image/v1.0/FR/4162/419/lr/room.jpg"/><HotelImage Type="卧室" URL="https://www.miki.co.uk/live/hotel/mikiNet/image/v1.0/FR/4162/419/lr/room1.jpg"/></酒店图片><酒店描述><LongDescription>这家 2 星级酒店位于尼斯市中心.很近到海滩.酒店设有餐厅.</LongDescription></酒店描述></附加信息></属性></属性></OTA_HotelAvailRS>

解决方案

把这个用于将 xml 转换为数组的类放在一个名为xmlParser.class.php"的文件中,将下面的代码复制粘贴到其中.

 $val){if($priority == '标签')$attributes_data[$attr] = $val;别的$result['attr'][$attr] = $val;}}if($type == "打开"){$parent[$level-1] = &$current;if(!is_array($current) 或 (!in_array($tag, array_keys($current)))){$current[$tag] = $result;如果($attributes_data)$current[$tag.'_attr'] = $attributes_data;$repeated_tag_index[$tag.'_'.$level] = 1;$current = &$current[$tag];}别的{if(isset($current[$tag][0])){$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;$repeated_tag_index[$tag.'_'.$level]++;}别的{$current[$tag] = array($current[$tag],$result);$repeated_tag_index[$tag.'_'.$level] = 2;if(isset($current[$tag.'_attr'])){$current[$tag]['0_attr'] = $current[$tag.'_attr'];未设置($current[$tag.'_attr']);}}$last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;$current = &$current[$tag][$last_item_index];}}elseif($type == "完成"){if(!isset($current[$tag])){$current[$tag] = $result;$repeated_tag_index[$tag.'_'.$level] = 1;if($priority == 'tag' 和 $attributes_data)$current[$tag.'_attr'] = $attributes_data;}别的{if(isset($current[$tag][0]) 和 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]++;}别的{$current[$tag] = array($current[$tag],$result);$repeated_tag_index[$tag.'_'.$level] = 1;if($priority == 'tag' 和 $get_attributes){if(isset($current[$tag.'_attr'])){$current[$tag]['0_attr'] = $current[$tag.'_attr'];未设置($current[$tag.'_attr']);}如果($attributes_data){$current[$tag][$repeated_tag_index[$tag.'_'.$level] .'_attr'] = $attributes_data;}}$repeated_tag_index[$tag.'_'.$level]++;}}}elseif($type == '关闭'){$current = &$parent[$level-1];}}返回($xml_array);}/*** @todo 将数组转换为 xml* @param 混合 $array* @param 字符串 $level* @param string $KeyForBlank* @access 公开* @return 混合*/公共函数 array_to_xml($array, $level=1, $KeyForBlank = 'row'){$xml = '';如果 ($level==1){$xml .= '<?xml version="1.0" encoding="UTF-8"?>'."<音乐盒><响应>";}否则如果($级别== 11){$xml .= '<?xml version="1.0" encoding="UTF-8"?>'."
"."";}foreach ($array as $key=>$value){$key = strtolower($key);$eleKey = $key;如果 (is_array($value)){if(sizeof($value)) {if ( preg_match('/^d+$/', $eleKey) ) $eleKey = $KeyForBlank;$xml .= str_repeat("",$level)."<$eleKey>";$level++;$xml .= $this->array_to_xml($value, $level, $KeyForBlank);$级别--;$xml .= str_repeat("",$level)."</$eleKey>";}别的{if($eleKey == '流派' || $this->ssBlankShow == true)$xml .= str_repeat("",$level)."<$eleKey></$eleKey>";别的$xml .= str_repeat("",$level)."<$eleKey/>";}}别的{如果(修剪($价值)!=''){if ( preg_match('/^d+$/', $eleKey) ) $eleKey = $KeyForBlank;if (htmlspecialchars($value)!=$value || $this->otherchar($value)){$xml .= str_repeat("",$level)."<$eleKey>$value</$eleKey>";}别的{$xml .= str_repeat("",$level)."<$eleKey>$value</$eleKey>";}}别的{if($eleKey == '流派' || $this->ssBlankShow == true)$xml .= str_repeat("",$level)."<$eleKey></$eleKey>";别的$xml .= str_repeat("",$level)."<$eleKey/>";}}}如果 ($level==1){$xml .= "</response></musicbox>";}否则如果($级别== 11){$xml .= "</xml>";}返回 $xml;}/*** @todo 删除其他字符 ('/:/')* @param 字符串 $str* @access 公开* @return 混合*/公共函数 otherchar($str){return preg_match('/:/', $str);}}

然后创建一个名为test.php"的文件,其中包含以下代码:

xml2array($ssString);$asArray1 = $oXmlParser->xml2array($ssString,'');$asArray2 = $oXmlParser->xml2array($ssString,1,'');echo "

";打印_r($asArray);出口;?>

试试这个,如果有任何不便,请告诉我,如果我能帮到你更多.

这是您通过更改如下参数得到的三种不同类型的数组,使用任何满足您需求的方法.

$asArray = $oXmlParser->xml2array($ssString);$asArray1 = $oXmlParser->xml2array($ssString,'');$asArray2 = $oXmlParser->xml2array($ssString,1,'');

I am new to SOAP. I am unable to convert this request into an array. This xml array should be in string type.

Xml request:

<OTA_HotelAvailRQ Version="1.0">
   <POS>
    <Source>
     <UniqueId Id="20000704abcde:105ABCDE" />
    </Source>
   </POS>
   <AvailRequestSegments>
    <AvailRequestSegment>
     <StayDateRange End="2011-08-15" Start="2011-08-14" />
     <RoomStayCandidates>
      <RoomStayCandidate Quantity="1">
       <GuestCounts>
        <GuestCount AgeQualifyingCode="10" Count="1" />
       </GuestCounts>
      </RoomStayCandidate>
     </RoomStayCandidates>
     <HotelSearchCriteria>
      <Criterion>
       <HotelRef Destination="East London, South Africa" CityCode="" CountryCode="" HotelName="" MinHotelRating="1"/>
       <SearchCurrency>EUR</SearchCurrency>
       <AdditionalInfo Value="1" />
       <Language>EN</Language>
      </Criterion>
     </HotelSearchCriteria>
    </AvailRequestSegment>
   </AvailRequestSegments>
  </OTA_HotelAvailRQ> 

xml response:

<OTA_HotelAvailRS Version="1.0">  
     <Success Id="24064"/>  
     <Properties>  
          <Property HotelCityCode="4162" HotelCode="6001287" HotelName="Amaryllis">  
               <RelativePosition Direction="" Distance="0" DistanceUnitName=""/>  
               <RoomStays>  
                    <RoomStay>  
                         <RatePlans>  
                              <RatePlan RatePlanCode="12201993"/>  
                         </RatePlans>  
                         <RoomRates>  
                              <RoomRate>  
                                   <Rates>  
                                        <Rate EffectiveDate="2010-06-12" ExpireDate="2010-06-13">  
                                             <Base Amount="76.00" CurrencyCode="EUR"/>  
                                             <RateDescription Adults="1" Availability="A" Children="0" RoomNum="1">  
                                                  <![CDATA[Single room]]>  
                                             </RateDescription>  
                                        </Rate>  
                                   </Rates>  
                              </RoomRate>  
                         </RoomRates>  
                         <Meals Description="Buffet B'Fast (continental)"/>  
                         <EssentialInfo>Here comes essential information</EssentialInfo> 
                    </RoomStay>                                        
               </RoomStays>  
               <Promotions/>  
               <AdditionalInfo>  
                    <HotelStarDetail rating="2"/>  
                    <HotelImages>  
                         <HotelImage Type="Bedroom" URL="https://www.miki.co.uk/live/hotel/mikiNet/image/v1.0/FR/4162/419/lr/room.jpg"/>  
                         <HotelImage Type="Bedroom"                                  URL="https://www.miki.co.uk/live/hotel/mikiNet/image/v1.0/FR/4162/419/lr/room1.jpg"/>  
                    </HotelImages>  
                    <HotelDescription>  
                         <LongDescription>This 2 star hotel is located in the city centre of Nice. It is close 
                         to the Beach. The Hotel has a restaurant.</LongDescription>  
                    </HotelDescription>  
               </AdditionalInfo>  
          </Property> 
     </Properties>  
</OTA_HotelAvailRS>

解决方案

Put this class for converting xml to array make a file named as "xmlParser.class.php" copy paste below code to it.

<?php
/**
 * xmlParser
 *
 * @author     shashank Patel
 */

class xmlParser
{
    public $ssBlankShow = true;

    /**
    * @todo convert xml to array
    * @param string $contents
    * @param string $get_attributes
    * @param string $priority
    * @access public
    * @return mixed
    */
    public 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);
    }

    /**
    * @todo convert array to xml
    * @param mixed $array 
    * @param string $level
    * @param string $KeyForBlank 
    * @access public    
    * @return mixed
    */
    public function array_to_xml($array, $level=1, $KeyForBlank = 'row')
    {
        $xml = '';

        if ($level==1) 
        {
            $xml .= '<?xml version="1.0" encoding="UTF-8"?>'.
                "<musicbox><response>";
        }
        else if($level==11)
        {
            $xml .= '<?xml version="1.0" encoding="UTF-8"?>'."
".
                "<xml>";
        }
        foreach ($array as $key=>$value) 
        {

            $key = strtolower($key);
            $eleKey = $key;

            if (is_array($value)) 
            {
                if(sizeof($value)) {
                    if ( preg_match('/^d+$/', $eleKey) ) $eleKey = $KeyForBlank;
                    $xml .= str_repeat("",$level)."<$eleKey>";
                    $level++;
                    $xml .= $this->array_to_xml($value, $level, $KeyForBlank);
                    $level--;
                    $xml .= str_repeat("",$level)."</$eleKey>";
                } 
                else 
                {   
                    if($eleKey == 'genre' || $this->ssBlankShow == true)
                        $xml .= str_repeat("",$level)."<$eleKey></$eleKey>";
                    else
                        $xml .= str_repeat("",$level)."<$eleKey />";
                }
            }
            else
            {
                if (trim($value)!='') 
                {
                    if ( preg_match('/^d+$/', $eleKey) ) $eleKey = $KeyForBlank;
                    if (htmlspecialchars($value)!=$value || $this->otherchar($value)) 
                    {
                        $xml .= str_repeat("",$level).
                                "<$eleKey>$value</$eleKey>";
                    } 
                    else 
                    {
                        $xml .= str_repeat("",$level).
                            "<$eleKey>$value</$eleKey>";
                    }
                }
                else 
                {
                    if($eleKey == 'genre' || $this->ssBlankShow == true)
                        $xml .= str_repeat("",$level)."<$eleKey></$eleKey>";
                    else
                        $xml .= str_repeat("",$level)."<$eleKey />";
                }
            }
        }
        if ($level==1) 
        {
            $xml .= "</response></musicbox>";
        }
        else if($level==11)
        {
            $xml .= "</xml>";
        }
        return $xml;
    }
    /**
    * @todo remove other char ('/:/')
    * @param string $str 
    * @access public    
    * @return mixed
    */


    public function otherchar($str)
    {
        return preg_match('/:/', $str);
    }

}

After that make a file named as "test.php" that contains below code:

<?php

$ssString = '<OTA_HotelAvailRQ Version="1.0"><POS><Source><UniqueId Id="20000704abcde:105ABCDE" /></Source></POS><AvailRequestSegments><AvailRequestSegment><StayDateRange End="2011-08-15" Start="2011-08-14" />
            <RoomStayCandidates><RoomStayCandidate Quantity="1"><GuestCounts><GuestCount AgeQualifyingCode="10" Count="1" /></GuestCounts></RoomStayCandidate></RoomStayCandidates>
            <HotelSearchCriteria><Criterion><HotelRef Destination="East London, South Africa" CityCode="" CountryCode="" HotelName="" MinHotelRating="1"/><SearchCurrency>EUR</SearchCurrency>
            <AdditionalInfo Value="1" /><Language>EN</Language></Criterion></HotelSearchCriteria></AvailRequestSegment></AvailRequestSegments></OTA_HotelAvailRQ>';

include 'xmlParser.class.php';

$oXmlParser = new xmlParser();
$asArray = $oXmlParser->xml2array($ssString);
$asArray1 = $oXmlParser->xml2array($ssString,'');
$asArray2 = $oXmlParser->xml2array($ssString,1,'');
echo "<pre>";
print_r($asArray);
exit;
?>

Try this if any inconvenience please inform me if i can help you more.

Here is three different kind array you got by changing parameters like below use whatever satisfy your demand.

$asArray = $oXmlParser->xml2array($ssString);

$asArray1 = $oXmlParser->xml2array($ssString,'');

$asArray2 = $oXmlParser->xml2array($ssString,1,'');

相关文章