2012-12-13 38 views
0

所以我有这些simplexmlelement对象。我不能让它工作如何解析一个特定的元素。我如何从这个列表中访问simplexml元素?

SimpleXMLElement Object 
(
[Generation] => SimpleXMLElement Object 
    (
     [@attributes] => Array 
      (
       [version] => 3.1.0-alpha3 
       [timestamp] => 1355434832 
      ) 

    ) 

[Options] => SimpleXMLElement Object 
    (
     [@attributes] => Array 
      (
       [tempFormat] => c 
       [byteFormat] => auto_binary 
       [refresh] => 60000 
       [showPickListTemplate] => true 
       [showPickListLang] => true 
      ) 

    ) 

[UsedPlugins] => SimpleXMLElement Object 
    (
    ) 

[Vitals] => SimpleXMLElement Object 
    (
     [@attributes] => Array 
      (
       [Hostname] => domain.tld 
       [IPAddr] => 127.0.0.1 
       [Kernel] => 2.6.32-11-pve (SMP) x86_64 
       [Distro] => Ubuntu 12.04.1 LTS 
       [Distroicon] => Ubuntu.png 
       [Uptime] => 1993669.51 
       [Users] => 1 
       [LoadAvg] => 0.08 0.02 0.01 
       [CPULoad] => 0 
      ) 

    ) 

....etc... 

    ) 

我做了这样的事情来访问主机名,例如:

echo $xml->Generation->Vitals[0]->Hostname; 

但我觉得我做错了什么。有人能指出我正确的方向吗?

回答

0

这纯粹是:

$xml->Vitals[0]->attributes()->Hostname 
+0

谢谢,我不知道如何impleme nt属性部分在那里。现在我已经学到了一些新的东西! – rsz

0

我不能完全肯定,如果你要坚持一个SimpleXml object,但如果你不这样做,看看在DOMDocumentDOMXPath组合。我很喜欢。要清楚,很难进入,但只要你掌握了它,你就会喜欢它。

你可以做这样的事情:

$doc = new DOMDocument(); 
$doc->load('http://www.example.com/file.xml'); 
$xpath = new DOMXPath($doc); 
$result = $xpath->query('//Vitals'); 

// print them all 
foreach ($result as $r){ 
    echo $r->getAttribute('Hostname'); //your desired value 
} 

// or just the first one 
echo $result->item(0)->getAttribute('Hostname'); 

你也可以将查询稍大获取属性马上像这样://[email protected]应该正常工作。

而这一开始,你可能会得到它的挂钩。

延伸阅读:

+0

有趣的我会看看它,但它似乎更容易 – rsz