简体   繁体   中英

To get all the child elements names and their values of a xml tag using php

I want to get all the child tag names and their values of a parent tag in a xml file using php .

My xml file looks like following

      <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>

I want to get all the child node names and their corresponding values of Building tag. For that I used following code

               //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

            }

But this code doesn't worked for me.
Help me.

Your code didn't work originally because your XML isn't valid because there is no root element. So when I added one in and printed out the values it worked fine:

$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 />';
}

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM