如何使用SimpleXML for PHP解析此XML?

时间:2011-03-28 20:38:14

标签: php xml simplexml

我正在尝试解析XML文档,但是我遇到了麻烦,因为我认为XML的格式化方式不适合使用SimpleXML。 XML中的某些元素可能包含0个或更多元素,我不知道如何使用SimpleXML正确地提取数据。由于本文档中的键名是数据类型,因此SimpleXML似乎将元素“聚集”在一起。我创建了一个简化的例子。

<?php
$xmlstr = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<results>
  <result kind="Host">
    <headings>
        <heading>Id</heading>
        <heading>Name</heading>
        <heading>IP Addresses</heading>
        <heading>DNS</heading>
        <heading>Timestamp</heading>
        <heading>Type</heading>
    </headings>
    <row>
        <string>38209387</string>
        <string>johnson38</string>
        <string>192.168.1.1</string>
        <string>joe.example.com</string>
        <datetime>Wed Sep  4 22:13:02 2009</datetime>
        <void/>
    </row>
    <row>
        <string>8283324</string>
        <string>smith42</string>
        <list>
            <string>192.168.1.7</string>
            <string>192.168.1.8</string>
        </list>
        <list>
            <string>john.example.com</string>
            <string>nick.example.com</string>
        </list>
        <datetime>Wed Oct  4 12:13:02 2009</datetime>
        <string>Major Server</string>
    </row>
  </result>
</results>
XML;


$xml = new SimpleXMLElement($xmlstr);
foreach ($xml->result->row as $row) {
    echo "<pre>";
    print_r($row);
    echo "</pre>";

    //display the 1st IP Address
    echo "IP Address: ".$row->string[2]."<br />";
}
?>

输出

 SimpleXMLElement Object
(
    [string] => Array
        (
            [0] => 38209387
            [1] => johnson38
            [2] => 192.168.1.1
            [3] => joe.example.com
        )

    [datetime] => Wed Sep  4 22:13:02 2009
    [void] => SimpleXMLElement Object
        (
        )

)
IP Address: 192.168.1.1
SimpleXMLElement Object
(
    [string] => Array
        (
            [0] => 8283324
            [1] => smith42
            [2] => Major Server
        )

    [list] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [string] => Array
                        (
                            [0] => 192.168.1.7
                            [1] => 192.168.1.8
                        )

                )

            [1] => SimpleXMLElement Object
                (
                    [string] => Array
                        (
                            [0] => john.example.com
                            [1] => nick.example.com
                        )

                )

        )

    [datetime] => Wed Oct  4 12:13:02 2009
)
IP Address: Major Server

1 个答案:

答案 0 :(得分:2)

$xml = new SimpleXMLElement($xmlstr);
foreach ($xml->result->row as $row) {
    //this will still have elements in order, so you'll have to count:
    $count = 1;
    foreach($row->children() as $child){
       //whatever you want.
       $count++
    }
    //if you only want ip (the 3rd node):
    var_dump($row->xpath('*[3]'));
}