0

我想在 PHP 中阅读以下结构。

<Listing>
<Unit_Type> 1 Bedroom </Unit_Type>
<Facilities>
<facility>Balcony</facility>
<facility>Basement parking</facility>
<facility>BBQ area</facility>
<facility>Built in wardrobes</facility>
<facility>Covered parking</facility>
</Facilities>
</Listing>

以下是我的代码。

$feeds = new DOMDocument();
$feeds->load("propspace.xml"); 
$properties = $feeds->getElementsByTagName("Listing");

foreach( $properties as $property ){
$unittype_tag = $property->getElementsByTagName("Unit_Type");
$unit_type = $unittype_tag->item(0)->nodeValue;

 } 

标签的数量<facility>可以是可变的。

任何帮助,将不胜感激。

4

2 回答 2

1

要阅读这些设施,只需调用getElementsByTagName("facility")$property

$feeds = new DOMDocument();
$feeds->load("propspace.xml"); 
$properties = $feeds->getElementsByTagName("Listing");

foreach( $properties as $property ){
  $unittype_tag = $property->getElementsByTagName("Unit_Type");
  $unit_type = $unittype_tag->item(0)->nodeValue;

  foreach($property->getElementsByTagName("facility") as $f){
    echo $f->nodeValue . "\n";
  }
} 

输出

阳台
地下停车场
烧烤区
内置衣柜
有盖停车场

演示

于 2013-02-12T10:01:52.503 回答
0
<?php

  $xml = '
   <Listing>
      <Unit_Type> 1 Bedroom </Unit_Type>
      <Facilities>
         <facility>Balcony</facility>
         <facility>Basement parking</facility>
         <facility>BBQ area</facility>
         <facility>Built in wardrobes</facility>
         <facility>Covered parking</facility>
      </Facilities>
   </Listing>';

  $feeds = new DOMDocument();
  $feeds->loadXML($xml); 
  $properties = $feeds->getElementsByTagName("Listing");

  foreach( $properties as $property )
  {
    $unittype_tag = $property->getElementsByTagName("Unit_Type");
    $unit_type = $unittype_tag->item(0)->nodeValue;
    $Facilities = $property->getElementsByTagName("facility")
    foreach($Facilities as $facility)
    {
      echo "<pre>";
      print_r($facility->nodeValue);
      echo "</pre>";
    }    
  }

?>
于 2013-02-12T10:19:11.057 回答