0

如何遍历此 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);
}
4

2 回答 2

1

参考:

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

?>
于 2013-08-14T06:49:05.610 回答
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
        )

)
于 2013-08-14T12:02:17.393 回答