0

所以我有这些 simplexmlelement 对象。而且我无法让它工作如何解析特定元素。

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;

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

4

2 回答 2

0

它只是:

$xml->Vitals[0]->attributes()->Hostname
于 2012-12-13T21:51:32.930 回答
0

我不完全确定您是否必须坚持使用 a SimpleXml object,但如果您不这样做,请查看DOMDocumentandDOMXPath组合。我很喜欢。需要明确的是,这很难进入,但一旦你掌握了它,你就会喜欢它。

你可以这样做:

$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');

您还可以使查询稍大一点,以便立即获取属性,如下所示://Vitals@Hostname这也应该有效。

有了这个开始,您可能会掌握它。

进一步阅读:

于 2012-12-13T22:02:35.560 回答