我必须使用带有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
答案 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
)