I've an XML ( $fileXML ) like:
<FatturaElettronicaHeader>
<CedentePrestatore>
<DatiAnagrafici>
<Anagrafica>
<Denominazione>MY STORE SRL</Denominazione>
<Cognome>Rossi</Cognome>
</Anagrafica>
</DatiAnagrafici>
</CedentePrestatore>
</FatturaElettronicaHeader>
I use this function to retrieve some values:
$xml = new DOMDocument();
$xml->loadXML($fileXML);
$xpath = new DOMXPath($xml);
$nodes = $xpath->query('//CedentePrestatore/DatiAnagrafici');
foreach ($nodes as $nodelist) {
$denominazione = $xpath->query( 'Anagrafica/Denominazione', $nodelist)->item(0)->nodeValue;
$cognome = $xpath->query( 'Anagrafica/Cognome', $nodelist)->item(0)->nodeValue;
}
It work great. But node Cognome is optional in the XML, so sometimes it doesn't exist, like:
<FatturaElettronicaHeader>
<CedentePrestatore>
<DatiAnagrafici>
<Anagrafica>
<Denominazione>MY SHOP2 SRL</Denominazione>
</Anagrafica>
</DatiAnagrafici>
</CedentePrestatore>
</FatturaElettronicaHeader>
Then my script get error: Trying to get property of non-object
How can I modify my code to assign at variable $cognome node value if exist, empty string "" in other cases?
$xpath->query( 'Anagrafica/Cognome', $nodelist)->item(0)is an object or not?