如何在PHP中将此XML请求转换为数组?

前端之家收集整理的这篇文章主要介绍了如何在PHP中将此XML请求转换为数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是SOAP的新手.我无法将此请求转换为数组.此xml数组应为字符串类型.

Xml请求:

<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响应:

<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>
将此类用于将xml转换为数组,将名为“xmlParser.class.PHP”的文件复制粘贴到代码下面.
<?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
    * @returnmixed
    */
    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    
    * @returnmixed
    */
    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"?>'."\n".
                "<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 />";
                }
            }
        }
        if ($level==1) 
        {
            $xml .= "</response></musicBox>";
        }
        else if($level==11)
        {
            $xml .= "</xml>";
        }
        return $xml;
    }
    /**
    * @todo remove other char ('/\:/')
    * @param string $str 
    * @access public    
    * @returnmixed
    */


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

}

之后,创建一个名为“test.PHP”的文件,其中包含以下代码

<?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;
?>

如果有任何不便,请尝试此操作,如果我能为您提供更多帮助,请通知我.

您可以通过更改以下参数来获得三种不同类型的数组,使用满足您需求的任何内容.

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

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

$asArray2 = $oXmlParser->xml2array($ssString,'');
原文链接:https://www.f2er.com/php/138964.html

猜你在找的PHP相关文章