在php中读取xml

时间:2013-02-12 09:53:56

标签: php xml domdocument

我想在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>标记的数量可以是变量。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分: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";
  }
} 

输出

  

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

Demo

答案 1 :(得分: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>";
    }    
  }

?>