使用php获取所有子元素名称及其xml标记的值

时间:2014-05-31 05:11:31

标签: php xml simplexml

我想使用php在xml文件中获取所有子标记名称及其父标记的值。

我的xml文件如下所示

      <Business>
         <Franchise>False</Franchise>
      </Business>
      <Building>
         <BathroomTotal>5</BathroomTotal>
         <BedroomsTotal>3</BedroomsTotal>
         <Appliances>Sauna</Appliances>
         <ConstructedDate>1977</ConstructedDate>
         <ExteriorFinish>Brick</ExteriorFinish>
         <FireplacePresent>False</FireplacePresent>
         <FireProtection>Security system</FireProtection>
         <HalfBathTotal>3</HalfBathTotal>
       </Building>

我想获取所有子节点名称及其对应的Building标记值。 为此,我使用了以下代码

               //some code                 
              $fsp =  $xml->saveXML();
              $s = new SimpleXMLElement($fsp);
           foreach ($s->Building->children() as $child)
            {
                 $name = $child->getName() ; //to get name
                 $value = $child; //to get value

            }

但是这段代码对我没用。
帮助我。

1 个答案:

答案 0 :(得分:0)

您的代码最初不起作用,因为您的XML无效,因为没有根元素。因此,当我添加一个并打印出值时,它工作正常:

$xml = <<<XML
<root>
    <Business>
       <Franchise>False</Franchise>
    </Business>
    <Building>
       <BathroomTotal>5</BathroomTotal>
       <BedroomsTotal>3</BedroomsTotal>
       <Appliances>Sauna</Appliances>
       <ConstructedDate>1977</ConstructedDate>
       <ExteriorFinish>Brick</ExteriorFinish>
       <FireplacePresent>False</FireplacePresent>
       <FireProtection>Security system</FireProtection>
       <HalfBathTotal>3</HalfBathTotal>
     </Building>
</root>
XML;

$simple = new SimpleXMLElement($xml);
foreach ($simple->Building->children() as $child)
{
     $name = $child->getName() ; //to get name
     $value = $child; //to get value
     echo 'Name: ' . $name . ', Value: ' . $value . '<br />';
}

输出:

Name: BathroomTotal, Value: 5
Name: BedroomsTotal, Value: 3
Name: Appliances, Value: Sauna
Name: ConstructedDate, Value: 1977
Name: ExteriorFinish, Value: Brick
Name: FireplacePresent, Value: False
Name: FireProtection, Value: Security system
Name: HalfBathTotal, Value: 3