2016-08-23 62 views
1

我必須在不知道節點的情況下使用XML讀取並解析XML文件。在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); 
      } 
     } 
    } 

這似乎是工作,但沒有按」 t用子節點打印節點,例如:

Invoices 
Invoices, Company 
Invoices, Documents 
Invoices, Documents, Document 
+2

您需要遍歷每個節點的孩子也是如此。 – jhmckimm

+0

@PaulCrovella我的錯誤。我習慣於使用[SimpleXML](http://php.net/manual/en/book.simplexml.php),因此我的錯誤假設。 – jhmckimm

回答

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 
) 
+0

Thanks @ paul-crovella,我用你的第一個解決方案不重複數組中的元素。謝謝 – Swim89

+0

現在我有一個問題...「if(!empty($ a)&&!in_array(implode(」,「,$ a),$ result)){」我還需要保存到另一個數組中節點的值。當我嘗試「$ xml-> value」時,我沒有任何價值...... – Swim89