在没有已知节点的情况下使用PHP中的XMLReader读取XML

时间:2016-08-23 16:07:18

标签: php xml xmlreader

我必须使用带有PHP的XMLReader读取和解析XML文件,而不知道节点。

我有这个文件:

<Invoices>
  <Company>
    <Name>Tuttobimbi Srl</Name>
  </Company>
  <Documents>
    <Document>
      <CustomerCode>0055</CustomerCode>
      <CustomerWebLogin></CustomerWebLogin>
      <CustomerName>Il Puffetto</CustomerName>
    </Document>
  </Documents>
</Invoices>

我会像这样解析它:

Invoices
Invoices, Company
Invoices, Company, Name
Invoices, Documents
Invoices, Documents, Document
etc...

我写了这段代码:

    while ($xml->read()) {
        if ($xml->nodeType == XMLReader::ELEMENT)
            array_push($a, $xml->name);

        if ($xml->nodeType == XMLReader::END_ELEMENT)
            array_pop($a);

        if ($xml->nodeType == XMLReader::TEXT) {
            if (!in_array(implode(",", $a), $result)) {
                $result[] = implode(",", $a);
            }
        }
    }

它似乎工作但不打印带有子节点的节点,例如:

Invoices
Invoices, Company
Invoices, Documents
Invoices, Documents, Document

1 个答案:

答案 0 :(得分:1)

您认为其中许多节点XMLReader::TEXT节点实际上是XMLReader::SIGNIFICANT_WHITESPACE

幸运的是,您可以完全放弃$xml->nodeType == XMLReader::TEXT检查并在遇到元素时构建结果。

示例:

while ($xml->read()) {
    if ($xml->nodeType == XMLReader::ELEMENT) {
        array_push($a, $xml->name);
        $result[] = implode(",", $a);
    }

    if ($xml->nodeType == XMLReader::END_ELEMENT) {
        array_pop($a);
    }
}

这会给你:

Array
(
    [0] => Invoices
    [1] => Invoices,Company
    [2] => Invoices,Company,Name
    [3] => Invoices,Documents
    [4] => Invoices,Documents,Document
    [5] => Invoices,Documents,Document,CustomerCode
    [6] => Invoices,Documents,Document,CustomerWebLogin
    [7] => Invoices,Documents,Document,CustomerName
)