2

How to get all the unique node names in XMLReader? Let's say for example I have below XML data:

<a>
    <b>
        <firstname>John</firstname>
        <lastname>Doe</lastname>
    </b>
    <c>
        <firstname>John</firstname>
        <lastname>Smith</lastname>
        <street>Streetvalue</street>
        <city>NYC</city>
    </c>
    <d>
        <street>Streetvalue</street>
        <city>NYC</city>
        <region>NY</region>
    </d>
</a>

How can I get firstname, lastname, street, city, region from above XML data using XMLReader? Also the file is very big, so need to see performance also while getting the node names.

Thanks

4

2 回答 2

3

我没有机会测试它,但试一试:

$reader = new XMLReader();
$reader->open($input_file);
$nodeList = array();

while ($reader->read())
{

    // We need to check if we're dealing with an Element
    if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'b')
    {
        // Let's inspect the node's content as well
        while ($reader->read())
        {
            if ($reader->nodeType == XMLReader::ELEMENT)
            {
                 // Saving the node to an auxiliar array
                 array_push($nodeList, $reader->localName);
            }
        }
}

// Finally, let's filter the array
$nodeList = array_unique($nodeList);

性能方面,如果文件很大,那么 XMLReader 是可行的方法,因为它只会将当前标签加载到内存中(而另一方面,DOMDocument 会加载所有内容)。 以下是有关可用于读取 XML 的三种技术的更详细说明。

顺便说一句,如果包含节点的数组变得太大,则更定期地运行 array_unique(而不是最后才这样做),以便修剪它。

于 2013-07-10T15:38:47.990 回答
1

您可以使用simplexml_load_file function.xml 文件加载 xml 数据PHP object。使用示例simplexml_load_string function

$xml_string = '<?xml version="1.0" encoding="UTF-8"?>
<a>
    <b>
        <firstname>John</firstname>
        <lastname>Doe</lastname>
    </b>
    <c>
        <firstname>John</firstname>
        <lastname>Smith</lastname>
        <street>Streetvalue</street>
        <city>NYC</city>
    </c>
    <d>
        <street>Streetvalue</street>
        <city>NYC</city>
        <region>NY</region>
    </d>
</a>';

$xml = simplexml_load_string($xml_string);
/* $xml = simplexml_load_file($file_name); */ // Use this to load xml data from file

// Data will be in $xml and you can iterate it like this
foreach ($xml as $x) {
    if (isset($x->firstname)) {
        echo $x->firstname . '<br>'; // $x->lastname, $x->street, $x->city also can be access this way
    }
}
于 2013-07-10T16:21:13.417 回答