使用PHP解析XML

时间:2014-01-07 07:25:24

标签: php xml

我正在使用SimpleXMLElement来解析PHP中的xml,它运行正常。我的xml就像,

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

我的代码是,

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

它提供正确的用户名“sample”作为输出。

但现在我需要在app标签中获得id的值。如果我更改了xml格式并将<app>标记内的ID设为<id>123</id>,我可以简单地理解它。

但我无法改变格式!有没有办法让id值在同一格式内?

1 个答案:

答案 0 :(得分:3)

试试这个:

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