如何将此xml响应更改为数组?

时间:2013-08-14 06:46:18

标签: php xml

如何遍历此xml并仅获取short_name和opted_in属性?

    <?xml version="1.0"?>
<CABS_ProviderOptIn_RS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.leisure.com/Schemas/CABS/1.0/CABS_ProviderOptIn_RS.xsd">
  <Status>
    <Success xmlns="http://www.leisure.com/Schemas/CABS/1.0/CABS_Common.xsd">success</Success>
  </Status>
  <Channels>
    <Channel id="Blue_Mountains_City_Tourism_Web" xmlns="http://www.leisure.com/Schemas/CABS/1.0/CABS_Common.xsd">
      <Providers>
        <Provider short_name="adam" content_id="OaksGoldApt" opted_in="true"  />
        <Provider short_name="ravi" content_id="9002005" opted_in="true"  />
        <Provider short_name="yoyo" content_id="QuestNthRde" opted_in="true"  />        
      </Providers>
    </Channel>
  </Channels>
</CABS_ProviderOptIn_RS>

我这样做却无法实现。

$xmlpar = simplexml_load_string('I put this xml here');

var_dump($xmlpar);

foreach($xmlpar as $x)
{
    var_dump($x);
}

2 个答案:

答案 0 :(得分:1)

Reference:

<?php

      $xmlpar = simplexml_load_string('I put this xml here');
      var_dump(toArray($xmlpar));


     function toArray(SimpleXMLElement $xml) {
         $array = (array)$xml;

         foreach ( array_slice($array, 0) as $key => $value ) {
             if ( $value instanceof SimpleXMLElement ) {
                 $array[$key] = empty($value) ? NULL : toArray($value);
             }
         }
         return $array;
     } 

?>

答案 1 :(得分:0)

试试这个

<?php
$k = '<?xml version="1.0"?>
<CABS_ProviderOptIn_RS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.leisure.com/Schemas/CABS/1.0/CABS_ProviderOptIn_RS.xsd">
  <Status>
    <Success xmlns="http://www.leisure.com/Schemas/CABS/1.0/CABS_Common.xsd">success</Success>
  </Status>
  <Channels>
    <Channel id="Blue_Mountains_City_Tourism_Web" xmlns="http://www.leisure.com/Schemas/CABS/1.0/CABS_Common.xsd">
      <Providers>
        <Provider short_name="adam" content_id="OaksGoldApt" opted_in="true"  />
        <Provider short_name="ravi" content_id="9002005" opted_in="true"  />
        <Provider short_name="yoyo" content_id="QuestNthRde" opted_in="true"  />        
      </Providers>
    </Channel>
  </Channels>
</CABS_ProviderOptIn_RS>';

$xmlpar = simplexml_load_string($k);
$chan = $xmlpar->Channels;
$Channel = $chan->Channel;
$Providers = $Channel->Providers;
$Provider= $Providers->Provider;
foreach($Provider as $pro)
{
$short_name[] =  $pro['short_name'];    
}
echo "<pre>";
print_r($short_name);

 ?>

输出:

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => adam
        )

    [1] => SimpleXMLElement Object
        (
            [0] => ravi
        )

    [2] => SimpleXMLElement Object
        (
            [0] => yoyo
        )

)