在php中使用属性读取xml

时间:2014-11-04 07:36:58

标签: php xml

我有一个xml。如附件中所示.. 我如何通过php

阅读内容

http://agency.lastminute-hr.com/slike/xml_read1.jpg" XML"

现在我读了这个xml:

<?

    $request            = new SimpleXMLElement('<HotelInfoRequest/>');
    $request->Username  = 'SERUNCD';
    $request->Password  = 'TA78UNC';
    $request->HotelID  = '123';



    $url    = "http://wl.filos.com.gr/services/WebService.asmx/HotelInfo";
    $result = simplexml_load_file($url . "?xml=" . urlencode($request->asXML()));



    function RecurseXML($xml,$parent="")
    {
       $child_count = 0;
       foreach($xml as $key=>$value)
       {
          $child_count++;   

          if(RecurseXML($value,$parent.".".$key) == 0)  // no childern, aka "leaf node"
          {

             print($parent . "." . (string)$key . " = " . (string)$value . "<BR>\n");       
          }    
       }
       return $child_count;
    } 

    RecurseXML($result); 
?>

这个结果看起来:

..
..
.Response.Hotels.Hotel.Rooms.Room.Quantity = 0
.Response.Hotels.Hotel.Rooms.Room.MaxPax = 3
.Response.Hotels.Hotel.Rooms.Room.MinPax = 2
.Response.Hotels.Hotel.Rooms.Room.RoomType.languages.lang = Room Double Standard
.Response.Hotels.Hotel.Rooms.Room.RoomType.languages.lang = Camera single standard
...
...

我需要您显示值和参与

<Rooms>
    <Room ID = "5556">
      <Quantity> 0 </ Quantity>
      <MaxPax> 3 </ MaxPax>
      <MinPax> 2 </ MinPax>
      <Roomtype> </ roomtype>
</ Room>
....
..

1 个答案:

答案 0 :(得分:1)

尝试(第一部分仅用于测试):

$string = <<<XML
<?xml version='1.0'?>
<Rooms>
    <Room ID = "5556">
      <Quantity> 0 </Quantity>
      <MaxPax> 3 </MaxPax>
      <MinPax> 2 </MinPax>
      <Roomtype> </Roomtype>
    </Room>
</Rooms>
XML;

$result = simplexml_load_string($string);

function RecurseXML($xml,$parent=".Response.Hotels.Hotel.Rooms"){
    $children = $xml->children();
    if ( empty($children) ) {
        print($parent . "." . $xml->nodeName .  " = " . (string)$xml . "<BR>\n");
    }
   else {
        foreach($children as $key=>$value) {
            RecurseXML($value, $parent . "." . $key);
        }
    }
}

RecurseXML($result);