Vishnu R
Vishnu R

Reputation: 1869

Parse XML using PHP

I am using SimpleXMLElement to parse xml in PHP and it is working fine. My xml is like,

<?xml version="1.0" encoding="ISO-8859-1"?>
<app id="123">
   <username>sample</username>
</app>

My code is,

$xml = new SimpleXMLElement(file_get_contents(file.xml));
foreach($xml->App as $product)
     {
          $user   =   $product->username;
     }

It gives correct username "sample" as output.

But now I need to get value of id inside the app tag. If I changes the xml format and gives the id inside <app> tag as <id>123</id>, I can get it simply.

But I cant change the format! Is there a way to get the id value within the same format?

Upvotes: 1

Views: 111

Answers (1)

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35963

try this:

     $xml = new SimpleXMLElement(file_get_contents(file.xml));
     foreach($xml->App as $product)
     {
          $user   =   $product->username;
          $id = $product->attributes()->id;
     }

Upvotes: 3

Related Questions