我有一个类似这样的变量的XML,其中“ FatturaElettronicaBody”可以出现1次以上:
$variable = '<Root>
<FatturaElettronicaBody>
<DatiGenerali>
<DatiGeneraliDocumento>
<TipoDocumento>TD01</TipoDocumento>
<Divisa>EUR</Divisa>
<Data>2018-12-31</Data>
<Numero>2140/18</Numero>
<ImportoTotaleDocumento>1843.71</ImportoTotaleDocumento>
<Causale>FATTURA DIFFERITA VENDITA</Causale>
</DatiGeneraliDocumento>
<Attachment>
<Filename>Test-1.pdf</Filename>
<Base64File>nfsofsedfmskd=.......</Base64File>
</Attachment>
<Attachment>
<Filename>Test-2.pdf</Filename>
<Base64File>nfsogfdgdfgdfsffsdgsmskd=.......</Base64File>
</Attachment>
...
</DatiGenerali>
</FatturaElettronicaBody>
<FatturaElettronicaBody>
<DatiGenerali>
<DatiGeneraliDocumento>
<TipoDocumento>TD01</TipoDocumento>
<Divisa>EUR</Divisa>
<Data>2018-10-29</Data>
<Numero>2094/18</Numero>
<ImportoTotaleDocumento>500.43</ImportoTotaleDocumento>
<Causale>FATTURA VENDITA</Causale>
</DatiGeneraliDocumento>
<Attachment>
<Filename>Test-N.pdf</Filename>
<Base64File>nfsogdhswvervsv.......</Base64File>
</Attachment>
</DatiGenerali>
</FatturaElettronicaBody>
...
</Root>
';
我的目标是在XML内搜索“ Numero”节点,并获取父节点“ DatiGeneraliDocumento”以显示有关找到的项目的信息。
例如,我需要找到Numero =“ 2094/18”并在其“ DatiGeneraliDocumento”节点内打印所有信息。在此示例中:
TipoDocumento = TD01
Divisa = EUR
Data = 2018-10-29
ImportoTotaleDocumento = 500.43
Causale = FATTURA VENDITA
PHP中是否有一个函数可以不循环我所有的$ variable?
更新:我已经修改了我的第一个请求,以同时获得“附件”节点:
例如,我需要找到Numero =“ 2094/18”并在其“ DatiGeneraliDocumento”节点和所有“ Attachment”中打印所有信息。在此示例中:
TipoDocumento = TD01
Divisa = EUR
Data = 2018-10-29
ImportoTotaleDocumento = 500.43
Causale = FATTURA VENDITA
Filename = Test-1.pdf
Base64File = nfsofsedfmskd=
Filename = Test-2.pdf
Base64File = nfsogfdgdfgdfsffsdgsmskd=
我尝试过运气:
$numeroFattura = "2094/18";
foreach ($xml->xpath('//DatiGenerali[Numero = "' . $numeroFattura . '"]') as $x) {
foreach($x as $v) {
echo $v->getName() .'='. $v ."<br>\n";
}
}
// GET ATTACHMENT <---this doesn't work
foreach ($xml->xpath('//FatturaElettronicaBody[Numero = "' . $numeroFattura . '"]') as $x) {
foreach ($x->xpath('//Allegati') as $allegato) {
var_dump($allegato);
}
}
答案 0 :(得分:1)
您可以使用PHP DOMDocument
和DOMXPath
提取所需的信息。通过在XPath查询中为Numero
指定节点值,我们仅获得您感兴趣的节点:
$doc = new DOMDocument();
$doc->loadXML($variable);
$xpath = new DOMXPath($doc);
$nodes = $xpath->query("//DatiGeneraliDocumento[Numero='2094/18']");
foreach ($nodes as $nodelist) {
foreach ($nodelist->childNodes as $node) {
if ($node->nodeType === XML_ELEMENT_NODE) echo $node->nodeName . " = " . $node->nodeValue . "\n";
}
}
输出:
TipoDocumento = TD01
Divisa = EUR
Data = 2018-10-29
Numero = 2094/18
ImportoTotaleDocumento = 500.43
Causale = FATTURA VENDITA
答案 1 :(得分:1)